What is SQL?
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 uses SQL as standard database language.
Also they are using different dialects, Such as:
- MS SQL Server using T-SQL,
- Oracle using PL/SQL,
- MS Access version of SQL is called JET SQL (native format )etc
History of SQL
SQL was initially developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. This version, initially called SEQUEL (Structured English Query Language), was designed to manipulate and retrieve data stored in IBM's original quasi-relational database management system, System R, which a group at IBM San Jose Research Laboratory had developed during the 1970s.The acronym SEQUEL was later changed to SQL because "SEQUEL" was a trademark of the UK-based Hawker Siddeley aircraft company.In the late 1970s, Relational Software, Inc. (now Oracle Corporation) saw the potential of the concepts described by Codd, Chamberlin, and Boyce and developed their own SQL-based RDBMS with aspirations of selling it to the U.S. Navy, Central Intelligence Agency, and other U.S. government agencies. In June 1979, Relational Software, Inc. introduced the first commercially available implementation of SQL, Oracle V2 (Version2) for VAX computers.
After testing SQL at customer test sites to determine the usefulness and practicality of the system, IBM began developing commercial products based on their System R prototype including System/38, SQL/DS, and DB2, which were commercially available in 1979, 1981, and 1983, respectively.
Why SQL?
- Allow users to access data in relational database management systems.
- Allow users to describe the data.
- Allow users to define the data in database and manipulate that data.
- Allow to embed within other languages using SQL modules, libraries & pre-compilers.
- Allow users to create and drop databases and tables.
- Allow users to create view, stored procedure, functions in a database.
- Allow users to set permissions on tables, procedures, and views
What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd.
What is table ?
The data in RDBMS is stored in database objects called tables. The table is a collection of related data entries and it consists of columns and rows.Remember, a table is the most common and simplest form of data storage in a relational database.
What is field?
Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.A field is a column in a table that is designed to maintain specific information about every record in the table.
What is record, or row?
A record, also called a row of data, is each individual entry that exists in a table. For example there are 7 records in the above CUSTOMERS table.A record is a horizontal entity in a table.
What is column?
A column is a vertical entity in a table that contains all information associated with a specific field in a table.What is NULL value?
A NULL value in a table is a value in a field that appears to be blank which means A field with a NULL value is a field with no value.It is very important to understand that a NULL value is different than a zero value or a field that contains spaces. A field with a NULL value is one that has been left blank during record creation.
SQL Constraints:
Constraints 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.Contraints could be column level or table level. Column level constraints are applied only to one column where as table level constraints are applied to the whole table.
SQL Syntax:
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 make difference in table names. So if you are working with MySQL then you need to give table names as they exist in the database.
SQL SELECT Statement:
SELECT column1, column2....columnN FROM table_name;
SQL DISTINCT Clause:
SELECT DISTINCT column1, column2....columnN FROM table_name;
SQL WHERE Clause:
SELECT column1, column2....columnN FROM table_name WHERE CONDITION;
SQL AND/OR Clause:
SELECT column1, column2....columnN FROM table_name WHERE CONDITION-1 {AND|OR} CONDITION-2;
SQL IN Clause:
SELECT column1, column2....columnN FROM table_name WHERE column_name IN (val-1, val-2,...val-N);
SQL BETWEEN Clause:
SELECT column1, column2....columnN FROM table_name WHERE column_name BETWEEN val-1 AND val-2;
SQL Like Clause:
SELECT column1, column2....columnN FROM table_name WHERE column_name LIKE { PATTERN };
SQL ORDER BY Clause:
SELECT column1, column2....columnN FROM table_name WHERE CONDITION ORDER BY column_name {ASC|DESC};
SQL GROUP BY Clause:
SELECT SUM(column_name) FROM table_name WHERE CONDITION GROUP BY column_name;
SQL COUNT Clause:
SELECT COUNT(column_name) FROM table_name WHERE CONDITION;
SQL HAVING Clause:
SELECT SUM(column_name) FROM table_name WHERE CONDITION GROUP BY column_name HAVING (arithematic function condition);
SQL CREATE TABLE Statement:
CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) );
SQL DROP TABLE Statement:
DROP TABLE table_name;
SQL CREATE INDEX Statement :
CREATE UNIQUE INDEX index_name ON table_name ( column1, column2,...columnN);
SQL DROP INDEX Statement :
ALTER TABLE table_name DROP INDEX index_name;
SQL DESC Statement :
DESC table_name;
SQL TRUNCATE TABLE Statement:
TRUNCATE TABLE table_name;
SQL ALTER TABLE Statement:
ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};
SQL ALTER TABLE Statement (Rename) :
ALTER TABLE table_name RENAME TO new_table_name;
SQL INSERT INTO Statement:
INSERT INTO table_name( column1, column2....columnN) VALUES ( value1, value2....valueN);
SQL UPDATE Statement:
UPDATE table_name SET column1 = value1, column2 = value2....columnN=valueN [ WHERE CONDITION ];
SQL DELETE Statement:
DELETE FROM table_name WHERE {CONDITION};
SQL CREATE DATABASE Statement:
CREATE DATABASE database_name;
SQL DROP DATABASE Statement:
DROP DATABASE database_name;
SQL USE Statement:
USE DATABASE database_name;
SQL COMMIT Statement:
COMMIT;
SQL ROLLBACK Statement:
ROLLBACK;
SQL - Operators:
SQL Arithmetic Operators:
Assume variable a holds 10 and variable b holds 20 then:Operator | Description | Example |
---|---|---|
+ | Addition - Adds values on either side of the operator | a + b will give 30 |
- | Subtraction - Subtracts right hand operand from left hand operand | a - b will give -10 |
* | Multiplication - Multiplies values on either side of the operator | a * b will give 200 |
/ | Division - Divides left hand operand by right hand operand | b / a will give 2 |
% | Modulus - Divides left hand operand by right hand operand and returns remainder | b % a will give 0 |
SQL Comparison Operators:
Assume variable a holds 10 and variable b holds 20 then:Operator | Description | Example |
---|---|---|
= | Checks if the value of two operands are equal or not, if yes then condition becomes true. | (a = b) is not true. |
!= | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. | (a != b) is true. |
<> | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. | (a <> b) is true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (a > b) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (a < b) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (a >= b) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (a <= b) is true. |
!< | Checks if the value of left operand is not less than the value of right operand, if yes then condition becomes true. | (a !< b) is false. |
!> | Checks if the value of left operand is not greater than the value of right operand, if yes then condition becomes true. | (a !> b) is true. |
SQL Logical Operators:
Here is a list of all the logical operators available in SQL.Show Examples
Operator | Description |
---|---|
ALL | The ALL operator is used to compare a value to all values in another value set. |
AND | The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause. |
ANY | The ANY operator is used to compare a value to any applicable value in the list according to the condition. |
BETWEEN | The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value. |
EXISTS | The EXISTS operator is used to search for the presence of a row in a specified table that meets certain criteria. |
IN | The IN operator is used to compare a value to a list of literal values that have been specified. |
LIKE | The LIKE operator is used to compare a value to similar values using wildcard operators. |
NOT | The NOT operator reverses the meaning of the logical operator with which it is used. Eg. NOT EXISTS, NOT BETWEEN, NOT IN etc. This is negate operator. |
OR | The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause. |
IS NULL | The NULL operator is used to compare a value with a NULL value. |
UNIQUE | The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates). |
SQL - Useful Functions:
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.
- SQL MAX Function - The SQL MAX aggregate function allows us to select the highest (maximum) value for a certain column.
- SQL MIN Function - The SQL MIN aggregate function allows us to select the lowest (minimum) value for a certain column.
- SQL AVG Function - The SQL AVG aggregate function selects the average value for certain table column.
- SQL SUM Function - The SQL SUM aggregate function allows selecting the total for a numeric column.
- 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.
- SQL String Functions - Complete list of SQL functions required to manipulate strings in SQL.
HOW TO CREATE USER
The statement
create user creates a user.
In the most simple form, the create user statement is one of the following three:
SQL> create user sujeet identified by sonu;
user-sujeet
password-sonu
sql> create user sujeet identified externally;
sql> create user sujeet identified globally as 'external_name';
The first one creates a local user, the second one creates an
external user while the last one creates
global user.
Default tablespaces
When a user is created, his default tablespace as well as his
temporary tablespace can be specified.
create user sujeet
identified by sonu
default tablespace ts_users
temporary tablespace ts_temp;
Locked users
A user can be created locked, that is, the user cannot connect to the database.
SQL> create user sujeet identified by passw0rd
account lock;
The user is now created, he can be granted some rights, for example the right to connect to the database:
SQL> grant connect to sonu;
Now, if the user tries to connect to the database, he will get ORA-28000:
SQL> connect sujeet/sonu
ERROR:
ORA-28000: the account is locked
The user can now be unlocked with an alter user statement:
SQL> alter user sujeet account unlock;
Which allows Alfredo to log on to the database now:
SQL> connect sujeet/sonu Connected. Expiring password
A user can be created such that he needs to change his password when he logs on. This is achieved with the
password expire option.
SQL> create user Archana identified by sona
password expire;
Now, Archana connecting:
SQL> connect Archana/sona
ERROR:
ORA-28001: the password has expired
Changing password for Archana
New password:
Assigning profiles
A user can be assigned a profile when (s)he is created.
create user berta profile appl_profile
The profile being assigned must be created
Displaying existing users
The dba_users view shows already created users.
Restrictions on passwords
The following restrictions apply to a password:
Public role
When a user is created, the role public is automatically assigned to this user.
However, the role is not visible in
dba_sys_privs nor
session_roles .
|
CREATE SCHEMA statement
The CREATE SCHEMA statement does NOT actually create a schema in Oracle. (Find out how to create a schema in Oracle.)The CREATE SCHEMA statement is used only to create objects (ie: tables, views) in your schema in a single SQL statement, instead of having to issue individual CREATE TABLE statements and CREATE VIEW statements.
If an error occurs creating any of the objects in the CREATE SCHEMA statement, the Oracle database will roll back all create statements (e: tables and view) in the CREATE SCHEMA statement.
The syntax for the CREATE SCHEMA statement is:
CREATE SCHEMA AUTHORIZATION schema_name
[create_table_statement]
[create_view_statement]
[grant_statement];
schema_name is the name of the schema (which is the same as your Oracle username that you are logged in as).create_table_statement is optional. It is a valid CREATE TABLE statement.
create_view_statement is optional. It is a valid CREATE VIEW statement.
grant_statement is optional. It is a valid GRANT statement.
CREATE SCHEMA statement - Example
The following is a CREATE SCHEMA statement (creating one table within the schema):CREATE SCHEMA AUTHORIZATION sujeet
CREATE TABLE products
( product_id number(10) not null,
product_name varchar2(50) not null,
category varchar2(50),
CONSTRAINT products_pk PRIMARY KEY (product_id));
This create schema statement creates a schema called sujeet. In this new schema, it creates one table called products.You can also create more than one table using the CREATE SCHEMA statement as follows:
CREATE SCHEMA AUTHORIZATION sujeet
CREATE TABLE products
( product_id number(10) not null,
product_name varchar2(50) not null,
category varchar2(50),
CONSTRAINT products_pk PRIMARY KEY (product_id)
)
CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
city varchar2(25),
CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id));
This CREATE SCHEMA statement would create two tables - products
and suppliers. If an error occurs creating either of these tables,
neither table will be created.Alternatively, you could have created these 2 tables using 2 individual CREATE TABLE statements as follows (while logged in sujeet):
CREATE TABLE products
( product_id number(10) not null,
product_name varchar2(50) not null,
category varchar2(50),
CONSTRAINT products_pk PRIMARY KEY (product_id));
CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
city varchar2(25),
CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id));
how to list name of all available schema.
sql> select username from dba_users;
to list schema, but i think, its not a right approach, because, user
and schema has many-to-many relation,which means I can't get all schema
name here.Create Schema
CREATE SCHEMA AUTHORIZATION <schema_name> <create table or view or grant statement>; |
|
conn / as sysdba CREATE USER uwclass IDENTIFIED BY uwclass DEFAULT TABLESPACE uwdata TEMPORARY TABLESPACE temp QUOTA 10M ON uwdata; GRANT create session TO uwclass; GRANT create table TO uwclass; GRANT create view TO uwclass; conn uwclass/uwclass -- first one that doesn't work (t3 does not exist) CREATE SCHEMA AUTHORIZATION uwclass CREATE TABLE t1 (tid NUMBER(10) PRIMARY KEY, last_name VARCHAR2(20)) CREATE TABLE t2 (tid NUMBER(10) PRIMARY KEY, last_name VARCHAR2(20)) CREATE VIEW t1t2_view AS SELECT t1.tid, t2.last_name FROM t1, t3 WHERE t1.tid = t2.tid GRANT select ON t1t2_view TO system; -- then one that does CREATE SCHEMA AUTHORIZATION uwclass CREATE TABLE t1 (tid NUMBER(10) PRIMARY KEY, last_name VARCHAR2(20)) CREATE TABLE t2 (tid NUMBER(10) PRIMARY KEY, last_name VARCHAR2(20)) CREATE VIEW t1t2_view AS SELECT t1.tid, t2.last_name FROM t1, t2 WHERE t1.tid = t2.tid GRANT select ON t1t2_view TO system; |
How can I query for all schema names ?
sql> SELECT * FROM dba_users
sql> SELECT username FROM dba_users
How to create Table in SQL.
CREATE TABLE Statement
The SQL CREATE TABLE statement allows you to create and define a table.The syntax for the SQL CREATE TABLE statement is:
CREATE TABLE table_name ( column1 datatype null/not null, column2 datatype null/not null, ... );Each column must have a datatype. The column should either be defined as "null" or "not null" and if this value is left blank, the database assumes "null" as the default.
For Example
CREATE TABLE suppliers ( supplier_id number(10) not null, supplier_name varchar2(50) not null, contact_name varchar2(50));
Practice Exercise #1:
Create an SQL table called customers that stores customer ID, name, and address information. The customer ID should be the primary key for the table.Solution:
The SQL CREATE TABLE statement for the customers table is:CREATE TABLE customers ( customer_id number(10) not null, customer_name varchar2(50) not null, address varchar2(50), city varchar2(50), state varchar2(25), zip_code varchar2(10), CONSTRAINT customers_pk PRIMARY KEY (customer_id) );
Practice Exercise #2:
Based on the departments table below, create an SQL table called employees that stores employee number, employee name, department, and salary information. The primary key for the employees table should be the employee number. Create a foreign key on the employees table that references the departments table based on the department_id field.CREATE TABLE departments ( department_id number(10) not null, department_name varchar2(50) not null, CONSTRAINT departments_pk PRIMARY KEY (department_id) );
Solution:
The SQL CREATE TABLE statement for the employees table is:CREATE TABLE employees ( employee_number number(10) not null, employee_name varchar2(50) not null, department_id number(10), salary number(6), CONSTRAINT employees_pk PRIMARY KEY (employee_number), CONSTRAINT fk_departments FOREIGN KEY (department_id) REFERENCES departments(department_id));
****************SQL STATEMENT******************************************
How to use CREATE STATEMENT
Creating a basic table involves naming the table and defining its columns and each column's data type.The SQL CREATE TABLE statement is used to create a new table.
Syntax:
Basic syntax of CREATE TABLE statement is as follows:CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) ); CREATE TABLE is the keyword telling the database system what you want to do.in this case, you want to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data type it is. The syntax becomes clearer with an example below.
A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. You can check complete detail at Create Table Using another Tables
Example:
Following is an example which creates a CUSTOMERS table with ID as primary key and NOT NULL are the constraints showing that these fileds can not be NULL while creating records in this table:SQL> 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) ); You can verify if your table has been created successfully by looking at the message displayed by the SQL server otherwise you can use DESC command as follows:
SQL> DESC CUSTOMERS; +---------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------+------+-----+---------+-------+ | ID | int(11) | NO | PRI | | | | NAME | varchar(20) | NO | | | | | AGE | int(11) | NO | | | | | ADDRESS | char(25) | YES | | NULL | | | SALARY | decimal(18,2) | YES | | NULL | | +---------+---------------+------+-----+---------+-------+ 5 rows in set (0.00 sec) Now you have CUSTOMERS table available in your database which you can use to store required information related to customers.
How to use DROP Statement
The SQL DROP TABLE statement is used to remove a table definition and all data, indexes, triggers, constraints, and permission specifications for that table.
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:
Basic syntax of DROP TABLE statement is as follows:DROP TABLE table_name;
Example:
Let us first verify CUSTOMERS table, and then we would delete it from the database:SQL> DESC CUSTOMERS; +---------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------+------+-----+---------+-------+ | ID | int(11) | NO | PRI | | | | NAME | varchar(20) | NO | | | | | AGE | int(11) | NO | | | | | ADDRESS | char(25) | YES | | NULL | | | SALARY | decimal(18,2) | YES | | NULL | | +---------+---------------+------+-----+---------+-------+ 5 rows in set (0.00 sec)This means CUSTOMERS table is available in the database, so let us drop it as follows:
SQL> DROP TABLE CUSTOMERS; Query OK, 0 rows affected (0.01 sec)Now if you would try DESC command then you would get error as follows:
SQL> DESC CUSTOMERS; ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't existHere TEST is database name which we are using for our examples.
How to use INSERT INTO
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax:
There are two basic syntax of INSERT INTO statement is as follows:INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)] VALUES (value1, value2, value3,...valueN);Here column1, column2,...columnN are the names of the columns in the table into which you want to insert data.
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. The SQL INSERT INTO syntax would be as follows:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example:
Following statements would create six records in CUSTOMERS table:INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'kaushik', 23, 'Kota', 2000.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Komal', 22, 'MP', 4500.00 );You can create a record in CUSTOMERS table using second syntax as follows:
INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );All the above statement would product following records in CUSTOMERS table:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+
Populate one table using another table:
You can populate data into a table through select statement over another table provided another table has a set of fields which are required to populate first table. Here is the syntax:INSERT INTO first_table_name [(column1, column2, ... columnN)] SELECT column1, column2, ...columnN FROM second_table_name [WHERE condition];
How to use UPDATE statement
The SQL UPDATE Query is used to modify the existing records in a table.You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be effected.
Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; You can combine N number of conditions using AND or OR operators.
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ Following is an example which would update ADDRESS for a customer whose ID is 6:
SQL> UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE ID = 6; Now CUSTOMERS table would have following records:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | Pune | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do not need to use WHERE clause and UPDATE query would be as follows:
SQL> UPDATE CUSTOMERS SET ADDRESS = 'Pune', SALARY = 1000.00; Now CUSTOMERS table would have following records:
+----+----------+-----+---------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+---------+ | 1 | Ramesh | 32 | Pune | 1000.00 | | 2 | Khilan | 25 | Pune | 1000.00 | | 3 | kaushik | 23 | Pune | 1000.00 | | 4 | Chaitali | 25 | Pune | 1000.00 | | 5 | Hardik | 27 | Pune | 1000.00 | | 6 | Komal | 22 | Pune | 1000.00 | | 7 | Muffy | 24 | Pune | 1000.00 | +----+----------+-----+---------+---------+
How to use DELETE STATEMENT
The SQL DELETE Query is used to delete the existing records from a table.You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted.
Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:DELETE FROM table_name WHERE [condition]; You can combine N number of conditions using AND or OR operators.
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ Following is an example which would DELETE a customer whose ID is 6:
SQL> DELETE FROM CUSTOMERS WHERE ID = 6;
Now CUSTOMERS table would have following records:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE clause and DELETE query would be as follows:
SQL> DELETE FROM CUSTOMERS; Now CUSTOMERS table would not have any record.
HOW TO USE TRUNCATE TABLE COMMAND
The SQL TRUNCATE TABLE command is used to delete complete data from an existing table.You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data.
Syntax:
The basic syntax of TRUNCATE TABLE is as follows:TRUNCATE TABLE table_name;
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ Following is the example to turncate:
SQL > TRUNCATE TABLE CUSTOMERS;
Now CUSTOMERS table is truncated and following would be output from SELECT statement:
SQL> SELECT * FROM CUSTOMERS; Empty set (0.00 sec)
How to use Select Statement
SQL SELECT Statement is used to fetch the data from a
database table which returns data in the form of result table. These
result tables are called result-sets.Syntax:
The basic syntax of SELECT statement is as follows:SELECT column1, column2, columnN FROM table_name; Here column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field then you can use following syntax:
SELECT * FROM table_name;
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ Following is an example which would fetch ID, Name and Salary fields of the customers available in CUSTOMERS table:
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS; This would produce following result:
+----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 1 | Ramesh | 2000.00 | | 2 | Khilan | 1500.00 | | 3 | kaushik | 2000.00 | | 4 | Chaitali | 6500.00 | | 5 | Hardik | 8500.00 | | 6 | Komal | 4500.00 | | 7 | Muffy | 10000.00 | +----+----------+----------+ If you want to fetch all the fields of CUSTOMERS table then use the following query:
SQL> SELECT * FROM CUSTOMERS; This would produce following result:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+
How to use WHERE CLAUSE
The SQL WHERE clause is used to specify a condition while fetching the data from single table or joining with multiple table.
If the given condition is satisfied then only it returns specific value from the table. You would use WHERE clause to filter the records and fetching only necessary records.
The WHERE clause not only used in SELECT statement, but it is also used in UPDATE, DELETE statement etc. which we would examine in subsequent chapters.
Syntax:
The basic syntax of SELECT statement with WHERE clause is as follows:SELECT column1, column2, columnN FROM table_name WHERE [condition]You can specify a condition using comparision or logical operators like >, <, =, LIKE, NOT etc. Below examples would make this concept clear.
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+Following is an example which would fetch ID, Name and Salary fields from the CUSTOMERS table where salary is greater than 2000:
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000;This would produce following result:
+----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 4 | Chaitali | 6500.00 | | 5 | Hardik | 8500.00 | | 6 | Komal | 4500.00 | | 7 | Muffy | 10000.00 | +----+----------+----------+Following is an example which would fetch ID, Name and Salary fields from the CUSTOMERS table for a customer with name Hardik. Here it is important to note that all the strings should be given inside single quotes ('') where as numeric values should be given without any quote as in above example:
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE NAME = 'Hardik';This would produce following result:
+----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 5 | Hardik | 8500.00 | +----+----------+----------+
How to use AND,OR operators
The SQL AND and OR operators are used to combile
multiple conditions to narrow data in an SQL statement. These two
operators are called conjunctive operators.These operators provide a means to make multiple comparisons with different operators in the same SQL statement.
The AND Operator:
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.Syntax:
The basic syntax of AND operator with WHERE clause is as follows:SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]...AND [conditionN]; You can combine N number of conditions using AND operator. For an action to be taken by the SQL statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE.
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ Following is an example which would fetch ID, Name and Salary fields from the CUSTOMERS table where salary is greater than 2000 AND age is less tan 25 years:
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000 AND age < 25; This would produce following result:
+----+-------+----------+ | ID | NAME | SALARY | +----+-------+----------+ | 6 | Komal | 4500.00 | | 7 | Muffy | 10000.00 | +----+-------+----------+
The OR Operator:
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.Syntax:
The basic syntax of OR operator with WHERE clause is as follows:SELECT column1, column2, columnN FROM table_name WHERE [condition1] OR [condition2]...OR [conditionN] You can combine N number of conditions using OR operator. For an action to be taken by the SQL statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE.
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ Following is an example which would fetch ID, Name and Salary fields from the CUSTOMERS table where salary is greater than 2000 OR age is less tan 25 years:
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000 OR age < 25; This would produce following result:
+----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 3 | kaushik | 2000.00 | | 4 | Chaitali | 6500.00 | | 5 | Hardik | 8500.00 | | 6 | Komal | 4500.00 | | 7 | Muffy | 10000.00 | +----+----------+----------+
HOW TO USE '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 (_)
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 SELECT FROM table_name WHERE column LIKE '_XXXX_' You can combine N number of conditions using AND or OR operators. Here XXXX could be any numberic or string value.
Example:
Here are number of examples showing WHERE part having different LIKE clause with '%' and '_' operators:Statement | Description |
---|---|
WHERE SALARY LIKE '200%' | Finds any values that start with 200 |
WHERE SALARY LIKE '%200%' | Finds any values that have 200 in any position |
WHERE SALARY LIKE '_00%' | Finds any values that have 00 in the second and third positions |
WHERE SALARY LIKE '2_%_%' | Finds any values that start with 2 and are at least 3 characters in length |
WHERE SALARY LIKE '%2' | Finds any values that end with 2 |
WHERE SALARY LIKE '_2%3' | Finds any values that have a 2 in the second position and end with a 3 |
WHERE SALARY LIKE '2___3' | Finds any values in a five-digit number that start with 2 and end with 3 |
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ Following is an example which would display all the records from CUSTOMERS table where SALARY starts with 200:
SQL> SELECT * FROM CUSTOMERS WHERE SALARY LIKE '200%';
This would produce following result:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+----------+-----+-----------+----------+
HOW TO USE "TOP" CLAUSE
The SQL TOP clause is used to fetch a TOP N number or X percent records from a table.
Note: All the databases do not support TOP clause. For example MySQL supports LIMIT clause to fetch limited number of records and Oracle uses ROWNUM to fetch limited number of records.
Syntax:
The basic syntax of TOP clause with SELECT statement would be as follows:SELECT TOP number|percent column_name(s) FROM table_name WHERE [condition]
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ Following is an example on SQL server which would fetch top 3 records from CUSTOMERS table:
SQL> SELECT TOP 3 * FROM CUSTOMERS;
This would produce following result:
+----+---------+-----+-----------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+---------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+---------+-----+-----------+---------+ If you are using MySQL server then, here is equivalent example:
SQL> SELECT * FROM CUSTOMERS LIMIT 3; This would produce following result:
+----+---------+-----+-----------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+---------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+---------+-----+-----------+---------+ If you are using Oracle server then, here is equivalent example:
SQL> SELECT * FROM CUSTOMERS WHERE ROWNUM <= 3;
This would produce following result:
+----+---------+-----+-----------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+---------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+---------+-----+-----------+---------+
HOW TO USE "ORDER BY" CLAUSE
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sorts query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause is as follows:SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be in column-list.
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ Following is an example which would sort the result in ascending order by NAME and SALARY:
SQL> SELECT * FROM CUSTOMERS ORDER BY NAME, SALARY;
This would produce following result:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | +----+----------+-----+-----------+----------+ Following is an example which would sort the result in descending order by NAME:
SQL> SELECT * FROM CUSTOMERS ORDER BY NAME DESC;
This would produce following result:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 7 | Muffy | 24 | Indore | 10000.00 | | 6 | Komal | 22 | MP | 4500.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | +----+----------+-----+-----------+----------+
ORDER BY WITH SORT clause
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sorts query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause which would be used to sort result in ascending or descending order is as follows:SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be in column-list.
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ Following is an example which would sort the result in ascending order by NAME and SALARY:
SQL> SELECT * FROM CUSTOMERS ORDER BY NAME, SALARY;
This would produce following result:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | +----+----------+-----+-----------+----------+ Following is an example which would sort the result in descending order by NAME:
SQL> SELECT * FROM CUSTOMERS ORDER BY NAME DESC;
This would produce following result:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 7 | Muffy | 24 | Indore | 10000.00 | | 6 | Komal | 22 | MP | 4500.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | +----+----------+-----+-----------+----------+ To fetch the rows with own preferred order, the SELECT query would as follows:
SQL> SELECT * FROM CUSTOMERS ORDER BY (CASE ADDRESS WHEN 'DELHI' THEN 1 WHEN 'BHOPAL' THEN 2 WHEN 'KOTA' THEN 3 WHEN 'AHMADABAD' THEN 4 WHEN 'MP' THEN 5 ELSE 100 END) ASC, ADDRESS DESC;
This would produce following result:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 2 | Khilan | 25 | Delhi | 1500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 6 | Komal | 22 | MP | 4500.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | +----+----------+-----+-----------+----------+ This will sort customers by ADDRESS in your ownoOrder of preference first and in a natural order for the remaining addresses. Also remaining Addresses will be sorted in the reverse alpha order.
HOW TO USE "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.
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:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ If you want to know the total amount of salary on each customer, then GROUP BY query would be as follows:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME;
This would produce following result:
+----------+-------------+ | NAME | SUM(SALARY) | +----------+-------------+ | Chaitali | 6500.00 | | Hardik | 8500.00 | | kaushik | 2000.00 | | Khilan | 1500.00 | | Komal | 4500.00 | | Muffy | 10000.00 | | Ramesh | 2000.00 | +----------+-------------+ Now let us has following table where CUSTOMERS table has following records with duplicate names:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Ramesh | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | kaushik | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Now again, if you want to know the total amount of salary on each customer, then GROUP BY query would be as follows:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME;
This would produce following result:
+---------+-------------+ | NAME | SUM(SALARY) | +---------+-------------+ | Hardik | 8500.00 | | kaushik | 8500.00 | | Komal | 4500.00 | | Muffy | 10000.00 | | Ramesh | 3500.00 | +---------+-------------+
HOW TO USE "DISTINCT" KEYWORD
The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records.
There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records.
Syntax:
The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows:SELECT DISTINCT column1, column2,.....columnN FROM table_name WHERE [condition]
Example:
Consider CUSTOMERS table is having following records:+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+ First let us see how the following SELECT query returns duplicate salary records:
SQL> SELECT SALARY FROM CUSTOMERS ORDER BY SALARY; This would produce following result where salary 2000 is coming twice which is a duplicate record from the original table.
+----------+ | SALARY | +----------+ | 1500.00 | | 2000.00 | | 2000.00 | | 4500.00 | | 6500.00 | | 8500.00 | | 10000.00 | +----------+ Now let us use DISTINCT keyword with the above SELECT query and see the result:
SQL> SELECT DISTINCT SALARY FROM CUSTOMERS ORDER BY SALARY; This would produce following result where we do not have any duplicate entry:
+----------+ | SALARY | +----------+ | 1500.00 | | 2000.00 | | 4500.00 | | 6500.00 | | 8500.00 | | 10000.00 | +----------+
HOW TO USE JOIN STATEMENT
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.Consider following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | 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 | +----+----------+-----+-----------+----------+(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+Now let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;This would produce following result:
+----+----------+-----+--------+ | ID | NAME | AGE | AMOUNT | +----+----------+-----+--------+ | 3 | kaushik | 23 | 3000 | | 3 | kaushik | 23 | 1500 | | 2 | Khilan | 25 | 1560 | | 4 | Chaitali | 25 | 2060 | +----+----------+-----+--------+Here it is noteable 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.
SQL Join Types:
There are different type of joins available in SQL:- INNER JOIN: returns rows when there is a match in both tables.
- LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
- RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
- FULL JOIN: returns rows when there is a match in one of the tables.
- SELF JOIN: is used to join a table to itself, as if the table were two tables, temporarily renaming at least one table in the SQL statement.
- CARTESIAN JOIN: returns the cartesian product of the sets of records from the two or more joined tables.
Sample SQL Queries
1.
Display all the information of the table?
A)
select * from emp;
2.
Display unique Jobs from table?
A)
select distinct job from emp;
3. List
the emps in the asc order of their Salaries?
A)
select * from emp order by sal asc;
4. List
the details of the emps in asc order of the Dptnos and desc of Jobs?
A)select
* from emp order by deptno asc,job desc;
5.
Display all the unique job groups in the descending order?
A)select
distinct job from emp order by job desc;
6.
Display all the details of all ‘Mgrs’
A)Select
* from emp where empno in ( select mgr from emp) ;
7. List
the emps who joined before 1981.
A)
select * from emp where hiredate < (’01-jan-81’);
8. List
the Empno, Ename, Sal, Daily sal of all emps in the asc order of Annsal.
A)
select empno ,ename ,sal,sal/30,12*sal annsal from emp order by annsal asc;
9.
Display the Empno, Ename, job, Hiredate, Exp of all Mgrs
A)
select empno,ename ,job,hiredate, months_between(sysdate,hiredate)
exp
from emp
where empno in (select mgr from emp);
10. List
the Empno, Ename, Sal, Exp of all emps working for Mgr 7369.
A)
select empno,ename,sal,exp from emp where mgr = 7369;
11.
Display all the details of the emps whose Comm. Is more than their Sal.
A)
select * from emp where comm. > sal;
12. List
the emps in the asc order of Designations of those joined after the second half
of 1981.
A)
select * from emp where hiredate > (’30-jun-81’) and
to_char(hiredate,’YYYY’)
= 1981 order by job asc;
13. List
the emps along with their Exp and Daily Sal is more than Rs.100.
A)
select * from emp where (sal/30) >100;
14. List
the emps who are either ‘CLERK’ or ‘ANALYST’ in the Desc order.
A)
select * from emp where job = ‘CLERK’ or job = ‘ANALYST’ order by job
desc;
15. List
the emps who joined on ,3-DEC-81,17-DEC-81, in asc order of seniority.
A)
select * from emp where hiredate in
(’01-may-81’,’03-dec-81’,’17-dec-
81’,’19-jan-80’)
order by hiredate asc;
16. List
the emp who are working for the Deptno 10 or20.
A)
select * from emp where deptno = 10 or deptno = 20 ;
17. List
the emps who are joined in the year 81.
A)
select * from emp where hiredate between ’01-jan-81’ and ’31-dec-81’;
18. List
the emps who are joined in the month of Aug 1980.
A)
select * from emp where hiredate between ’01-aug-80’ and ’31-
aug-80’;
(OR)
select *
from emp where to_char(hiredate,’mon-yyyy’) =’aug-1980;
19. List
the emps Who Annual sal ranging from 22000 and 45000.
A)
select * from emp where 12*sal between 22000 and 45000;
20. List
the Enames those are having five characters in their Names.
A)
select ename from emp where length (ename) = 5;
21. List
the Enames those are starting with ‘S’ and with five characters.
A)
select ename from emp where ename like ‘S%’ and length (ename) = 5;
22. List
the emps those are having four chars and third character must be ‘r’.
A)
select * from emp where length(ename) = 4 and ename like ‘__R%’;
23. List
the Five character names starting with ‘S’ and ending with ‘H’.
A)
select * from emp where length(ename) = 5 and ename like ‘S%H’;
24. List
the emps who joined in January.
A)
select * from emp where to_char (hiredate,’mon’) = ‘jan’;
25. List
the emps who joined in the month of which second character is ‘a’.
A)
select * from emp where to_char(hiredate,’mon’) like ‘_a_’;
(OR)
B)
select * from emp where to_char(hiredate,’mon’) like ‘_a%’;
26. List
the emps whose Sal is four digit number ending with Zero.
A)
select * from emp where length (sal) = 4 and sal like
‘%0’;
27. List
the emps whose names having a character set ‘ll’ together.
A)
select * from emp where ename like
‘%LL%’;
28. List
the emps those who joined in 80’s.
A)
select * from emp where to_char(hiredate,’yy’) like ‘8%’;
29. List
the emps who does not belong to Deptno 20.
A)
select * from emp where deptno not in (20); (OR)
B)
select * from emp where deptno != 20; (OR)
C)
select * from emp where deptno <>20; (OR)
D)
select * from emp where deptno not like ‘20’;
30. List
all the emps except ‘PRESIDENT’ & ‘MGR” in asc order of Salaries.
A)
Select * from emp where job not in (‘PRESIDENT’,’MANAGER’) order
by
sal asc;
B)
select * from emp where job not like ‘PRESIDENT’ and job not like
‘MANAGER’
order by sal asc;
C)
Select * from emp where job != ‘PRESIDENT’ and job <> ‘MER’
order
by sal asc;
31. List
all the emps who joined before or after 1981.
A)
select * from emp where to_char (hiredate,’YYYY’) not in (‘1981’);
(OR)
B)
select * from emp where to_char ( hiredate,’YYYY’) !=
‘1981’; (OR)
C)
select * from emp where to_char(hiredate,’YYYY’) <> ‘1981’ ;
(OR)
D)
select * from emp where to_char (hiredate ,’YYYY’) not like ‘1981’;
32. List
the emps whose Empno not starting with digit78.
A)
select * from emp where empno not like ‘78%’;
33. List
the emps who are working under ‘MGR’.
A)
select e.ename || ‘ works for ‘ || m.ename from emp e ,emp m where e.mgr
=
m.empno
; (OR)
B)
select e.ename || ‘ has an employee ‘|| m.ename from emp e , emp m where
e.empno
= m.mgr;
34. List
the emps who joined in any year but not belongs to the month of March.
A)
select * from emp where to_char (hiredate,’MON’) not in
(‘MAR’); (OR)
B)
select * from emp where to_char (hiredate,’MON’) != ‘MAR’;
(OR)
C)
select * from emp where to_char(hiredate,’MONTH’) not like ‘MAR%’ ;
(OR)
D)
select * from emp where to_char(hiredate,’MON’) <> ‘MAR’;
35. List
all the Clerks of Deptno 20.
A)select
* from emp where job =‘CLERK’ and deptno = 20;
36. List
the emps of Deptno 30 or 10 joined in the year 1981.
A)
select * from emp where to_char(hiredate,’YYYY’) = ‘1981’ and (deptno =30
or
deptno =10) ; (OR) select * from emp where to_char
(hiredate,’YYYY’) in
(‘1981’)
and (deptno = 30 or deptno =10 ) ;
37.
Display the details of SMITH.
A)
select * from emp where ename = ‘SMITH’ ;
38.
Display the location of SMITH.
A)
select loc from emp e , dept d where e.ename = ‘SMITH’ and
e.deptno =
d.deptno
;
39. List
the total information of table along with DNAME and Loc of all the
emps
Working Under ‘ACCOUNTING’ & ‘RESEARCH’ in the asc Deptno.
A)
select * from emp e ,dept d where (dname = ‘ACCOUNTING’ or dname
=’RESEARCH’
) and e.deptno = d.deptno order by e.deptno asc; (OR)
B)
select * from emp e ,dept d where d.dname in
(‘ACCOUNTING’,’RESEARCH’)
and e.deptno = d.deptno order by e.deptno
asc;
40. List
the Empno, Ename, Sal, Dname of all the ‘MGRS’ and ‘ANALYST’
working
in , with an exp more than 7 years without receiving the
Comm asc
order of Loc.
A)
select e.empno,e.ename,e.sal,d.dname from emp e ,dept d where d.loc
in (‘NEW
’,’’) and
e.deptno = d.deptno and e.empno in (select e.empno
from emp
e where e.job in (‘MANAGER’,’ANALYST’) and
(months_between(sysdate,e.hiredate)/12)>
7 and e.comm. is null)
order by
d.loc asc;
41.
Display the Empno, Ename, Sal, Dname, Loc, Deptno, Job of all emps working at
CJICAGO
or working for ACCOUNTING dept with Ann Sal>28000, but the Sal
should
not be=3000 or 2800 who doesn’t belongs to the Mgr and whose no is
having a
digit ‘7’ or ‘8’ in 3 rd position in the asc order of Deptno and desc order
of job.
A)
select E.empno,E.ename,E.sal,D.dname,D.loc,E.deptno,E.job
from emp
E,dept D
where
(D.loc = '' or D.dname = 'ACCOUNTING') and
E.deptno=D.deptno
and E.empno in
(select
E.empno from emp E where (12*E.sal) > 28000 and E.sal not in
(3000,2800)
and E.job !='MANAGER'
and (
E.empno like '__7%' or E.empno like '__8%'))
order by
E.deptno asc , E.job desc;
42.
Display the total information of the emps along with Grades in the asc order.
A)
select * from emp e ,salgrade s where e.sal between s.losal and s.hisal
order
by grade
asc; (OR)
B)
select * from emp e ,salgrade s where e.sal >= s.losal and e.sal <=
s.hisal
order by
s.grade asc; (using between and
is a bit simple)
43. List
all the Grade2 and Grade 3 emps.
A)
select * from emp e where e.empno in (select e.empno from emp
e
,salgrade s where e.sal between s.losal and s.hisal and s.grade
in(2,3));
(OR)
B)
select * from emp e ,salgrade s where e.sal between s.losal and s.hisal
and s.grade in (2,3) ;
44.
Display all Grade 4,5 Analyst and Mgr.
A)
select * from emp e, salgrade s where e.sal between s.losal and s.hisal
and
s.grade
in (4,5) and e.empno in (select e.empno from emp e where e.job in
(‘MANAGER’,’ANALYST’)
);
45. List
the Empno, Ename, Sal, Dname, Grade, Exp, and Ann Sal of emps working
for
Dept10 or20.
A) selectE.empno,E.ename,E.sal,S.grade,D.dname,(months_between(sysdate,E.hired
ate)/12)
"EXP" ,12*E.sal “ANN SAL”
from emp
E,dept D ,salgrade S
where
E.deptno in (10,20) and E.deptno = D.deptno and E.sal between
S.losal
and
S.hisal ;
46. List
all the information of emp with Loc and the Grade of all the emps belong to
the
Grade range from 2 to 4 working at the Dept those are not starting with char
set ‘OP’
and not ending with ‘S’ with the designation having a char ‘a’ any where
joined
in the year 1981 but not in the month of Mar or Sep and Sal not end with
‘00’ in
the asc order of Grades
A) select e.empno,e.ename,d.loc,s.grade,e.sal
from emp e ,dept d,salgrade s
where
e.deptno = d.deptno
and
(d.dname not like 'OP%' and d.dname not like '%S') and e.sal between s.losal
and
s.hisal and s.grade in (2,3,4)
and
empno in (select empno from emp where job like '%A%'and sal not like ''
and
(to_char (hiredate,'YYYY') = '1981'
and
to_char(hiredate,'MON') not in ('MAR','SEP')));
47. List
the details of the Depts along with Empno, Ename or without the emps
A)
select * from emp e,dept d where e.deptno(+)= d.deptno;
48. List
the details of the emps whose Salaries more than the employee BLAKE.
A)
select * from emp where sal > (select sal from emp where ename =
‘BLAKE’);
49. List
the emps whose Jobs are same as ALLEN.
A)
select * from emp where job = (select job from emp where ename =
‘ALLEN’);
50. List
the emps who are senior to King.
A)
select * from emp where hiredate < ( select hiredate from emp
where
ename = ‘KING’);
51. List
the Emps who are senior to their own MGRS.
A)
select * from emp w,emp m where w.mgr = m.empno and
w.hiredate
< m.hiredate ; (OR)
B)
select * from emp w,emp m where w.empno= m.mgr and
w.hiredate>
m.hiredate;
52. List
the Emps of Deptno 20 whose Jobs are same as Deptno10.
A)
select * from emp e ,dept d where d.deptno = 20 and e.deptno = d.deptno and
e.job in
( select e.job from emp e,dept d where e.deptno = d.deptno and d.deptno
=10);
53. List
the Emps whose Sal is same as or SMITH in desc order of Sal.
A)
Select * from emp where sal in (select sal from emp where ( ename =
‘SMITH’
or
ename = ‘’ )) order by sal desc;
54. List
the emps Whose Jobs are same as MILLER or Sal is more than ALLEN.
A)
select * from emp where job = (select job from emp
where ename =
‘MILLER’
) or sal>(select sal from emp where ename = ‘ALLEN’);
55. List
the Emps whose Sal is > the total remuneration of the SALESMAN.
A)
select * from emp where sal >(select sum(nvl2(comm,sal+comm,sal)) from
emp
where job = ‘SALESMAN’);
56. List
the emps who are senior to BLAKE working at & .
A)
select * from emp e ,dept d where d.loc in
(‘’,’’) and
e.deptno = d.deptno and
e.hiredate
<(select e.hiredate from emp e where e.ename =
‘BLAKE’)
;
57. List
the Emps of Grade 3,4 belongs to the dept ACCOUNTING and RESEARCH
whose
Sal is more than ALLEN and exp more than SMITH in the asc order of
EXP.
A)
select * from emp e where e.deptno in (select d.deptno from
dept d
where d.dname in (‘ACCOUNTING’,’RESEARCH’) )
and
e.sal >(select sal from emp where ename = ‘ALLEN’) and
e.hiredate
<( select hiredate from emp where ename = ‘SMITH’) and
e.empno
in (select e.empno from emp e ,salgrade s where e.sal
between
s.losal and s.hisal and s.grade in (3,4) )
order by
e.hiredate desc;
58. List
the emps whose jobs same as SMITH or ALLEN.
A)
select * from emp where job in (select job from emp where
ename =
‘SMITH’ or ename = ‘ALLEN’); (OR)
B)
select * from emp where job in (select job from emp where ename in
(‘SMITH’,’ALLEN’);
59.
Write a Query to display the details of emps whose Sal is same as of
a)
Employee Sal of 1 table.
b) ¾ Sal
of any Mgr of 2 table.
c) The
sal of any person with exp of 5 years belongs to the sales dept of
emp3
table.
d) Any
grade 2 employee of emp4 table.
e) Any
grade 2 and 3 employee working fro sales dept or operations dept
joined
in 89.
60. Any
jobs of deptno 10 those that are not found in deptno 20.
A)
select e.job from emp e where e.deptno = 10 and e.job not in (select job
from
emp
where deptno =20);
61. List
of emps of emp1 who are not found in emp2.
62. Find
the highest sal of table.
A)
select max(sal) from emp;
63. Find
details of highest paid employee.
A)
select * from emp where sal in (select max(sal) from emp);
64. Find
the highest paid employee of sales department.
A)
select * from emp where sal in (select max(sal) from emp where deptno in
(select
d.deptno from dept d where d.dname = 'SALES'));
65. List
the most recently hired emp of grade3 belongs to location .
A)
select * from emp e where e.deptno in ( select d.deptno from dept d
where
d.loc =
'') and e.hiredate in (select max(hiredate) from emp where empno in
(select empno from emp e,salgrade s where e.sal between s.losal and
s.hisal and s.grade = 3)) ; (or)
select *
from emp e,dept d where d.loc=''
and
hiredate in(select max(hiredate) from emp e,salgrade s
where
sal between losal and hisal and grade=3);
66. List
the employees who are senior to most recently hired employee working
under
king.
A)
select * from emp where hiredate < (select max(hiredate) from emp where mgr
in
(select empno from emp where ename = 'KING')) ;
67. List
the details of the employee belongs to newyork with grade 3 to 5 except
‘PRESIDENT’
whose sal> the highest paid employee of in a group
where
there is manager and salesman not working under king
A)
select * from emp where deptno in (select deptno from dept where dept.loc
='')
and
empno in (select empno from emp e,salgrade s where e.sal between s.losal
and
s.hisal and
s.grade
in (3,4,5) ) and job != 'PRESIDENT' and sal >(select max(sal) from emp
where
deptno in
(select
deptno from dept where dept.loc = '') and job in
('MANAGER','SALESMAN')
and
mgr not
in (select empno from emp where ename = 'KING'));
68. List
the details of the senior employee belongs to 1981.
A)
select * from emp where hiredate in (select min(hiredate) from
emp
where to_char( hiredate,’YYYY’) = ‘1981’); (OR) B) select *
from emp where hiredate = (select min(hiredate) from
emp
where to_char(hiredate,’YYYY’) = ‘1981’);
69. List
the employees who joined in 1981 with the job same as the most senior
person
of the year 1981.
A)select
* from emp where job in (select job from emp where hiredate in
(select
min(hiredate) from emp where to_char(hiredate,’YYYY’) =’1981’));
70. List
the most senior empl working under the king and grade is more than 3.
A)
select * from emp where hiredate in (select min(hiredate) from emp where
empno in
(select
empno from emp e ,salgrade s where e.sal between s.losal and s.hisal and
s.grade
in (4,5)))
and mgr
in (select empno from emp where ename = 'KING');
71. Find
the total sal given to the MGR.
A)
select sum (sal) from emp where job = ‘MANAGER’; (OR)
B)
select sum(sal) from emp where empno in(select mgr from emp);
72. Find
the total annual sal to distribute job wise in the year 81.
A)
select job,sum(12*sal) from emp where to_char(hiredate,'YYYY') = '1981'
group by
job ;
73.
Display total sal employee belonging to grade 3.
A)
select sum(sal) from emp where empno
in
(select empno from emp e ,salgrade s
where
e.sal between s.losal and s.hisal and s.grade = 3)
74.
Display the average salaries of all the clerks.
A)
select avg(sal) from emp where job = ‘CLERK’;
75. List
the employeein whose sal is >the average sal 0f emps.
A)
select * from emp where deptno =20 and sal >(select avg (sal) from emp
where
deptno = 10);
76.
Display the number of employee for each job group deptno wise.
A)
select deptno ,job ,count(*) from emp group by deptno,job;
(or)
B)
select d.deptno,e.job,count(e.job) from emp e,dept d where
e.deptno(+)=d.deptno
group by e.job,d.deptno;
77. List the manage rno and the number of employees
working for those mgrs in the
ascending
Mgrno.
A)
select w.mgr ,count(*) from emp w,emp m
where
w.mgr = m.empno
group by
w.mgr
order by
w.mgr asc;
78. List
the department,details where at least two emps are working
A)
select deptno ,count(*) from emp group by deptno
having
count(*) >= 2;
79.
Display the Grade, Number of emps, and max sal of each grade.
A)
select s.grade ,count(*),max(sal) from emp e,salgrade s where e.sal between
s.losal
and s.hisal
group by
s.grade;
80.
Display dname, grade, No. of emps where at least two emps are clerks.
A)
select d.dname,s.grade,count(*) from emp e,dept d,salgrade s where e.deptno =
d.deptno
and
e.job =
'CLERK' and e.sal between s.losal and s.hisal group by d.dname,s.grade
having
count(*) >= 2;
81. List
the details of the department where maximum number of emps are working.
A)
select * from dept where deptno in
(select
deptno from emp group by
deptno
having
count(*) in
(select
max(count(*)) from emp group by deptno) ); (OR)
B)
select d.deptno,d.dname,d.loc,count(*) from emp e ,dept d
where
e.deptno = d.deptno group by d.deptno,d.dname,d..loc
having
count(*) = (select max(count(*) ) from emp group by deptno);
82.
Display the emps whose manager name is jones.
A)
select * from emp where mgr in
(select
empno from emp where ename = ‘JONES’); (OR)
B)
select * from emp where mgr =
(select
empno from emp where ename = ‘JONES’);
83. List
the employees whose salary is more than 3000 after giving 20% increment.
A)
SELECT * FROM WHERE (1.2*SAL) > 3000 ;
84. List
the emps with dept names.
A)
select
e.empno,e.ename,e.job,e.mgr,e.hiredate,e.sal,e.comm,e.deptno,d.dname
from
emp e ,dept d where e.deptno = d.deptno;
85. List
the emps who are not working in sales dept.
A) select * from emp where deptno
not in
(select
deptno from emp where dname = ‘SALES’);
86. List
the emps name ,dept, sal and comm. For those whose salary is between 2000
and 5000
while loc is .
A)
select e.ename,e.deptno,e.sal,e.comm from emp e ,dept d where e.deptno =
d.deptno
and
d.loc =
'' and e.sal between 2000 and 5000;
87. List
the emps whose sal is greater than his managers salary
A)
select * from emp w,emp m where w.mgr = m.empno and w.sal > m.sal;
88. List
the grade, name for the deptno 10 or deptno 30 but sal grade is not 4
while
they joined the company before ’31-dec-82’.
A)
select s.grade ,e.ename from emp e,salgrade s where e.deptno in (10,20)
and
hiredate
< ('31-DEC-82') and (e.sal between s.losal and s.hisal and s.grade not in
(4));
89. List
the name ,job, dname, location for those who are working as MGRS.
A)
select e.ename,e.job,d.dname,d.loc from emp e ,dept d
where
e.deptno = d.deptno and
e.empno
in (select mgr from emp ) ;
90. List
the emps whose mgr name is jones and also list their manager name.
A)
select w.empno,w.ename,w.job,w.mgr,w.hiredate,w.sal,w.deptno,m.ename
from emp
w ,emp m
where
w.mgr = m.empno and m.ename = 'JONES';
91. List
the name and salary of ford if his salary is equal to hisal of his grade.
A)
select e.ename,e.sal from emp e ,salgrade s where e.ename = '' and e.sal
between
s.losal and s.hisal and e.sal = s.hisal ;
92. Lit
the name, job, dname ,sal, grade dept wise
A)
select e.ename,e.job,d.dname,e.sal,s.grade from emp e,dept
d,salgrade
s
where
e.deptno = d.deptno and e.sal between s.losal and s.hisal
order
by e.deptno ;
93. List
the emp name, job, sal, grade and dname except clerks and sort on the basis
of
highest sal.
A) select e.ename,e.job,e.sal,s.grade,d.dname from emp e ,dept d
,salgrade
s where e.deptno = d.deptno and e.sal between s.losal
and
s.hisal and
e.job
not in('CLERK')
order
by e.sal desc;
94. List
the emps name, job who are with out manager.
A) select
e.ename,e.job from emp e where mgr is null;
95. List
the names of the emps who are getting the highest sal dept wise.
A)
select e.ename,e.deptno from emp e where e.sal in
(select
max(sal) from emp group by deptno) ;
96. List
the emps whose sal is equal to the average of max and minimum
A)
select * from emp where sal =(select (max(sal)+min(sal))/2 from
emp);
97. List
the no. of emps in each department where the no. is more than 3.
A)
select deptno,count(*) from emp group by deptno having count(*) < 3;
98. List
the names of depts. Where atleast 3 are working in that department.
A)
select d.dname,count(*) from emp e ,dept d where e.deptno =
d.deptno
group by d.dname having count(*) >= 3 ;
99. List
the managers whose sal is more than his employess avg salary.
A)
select * from emp m where m.empno in (select mgr from emp)
and m.sal > (select avg(e.sal) from emp e where e.mgr = m.empno
)
The
subquery does the same as (select (avg(e.sal)),m.ename from emp
e,emp m
where e.mgr=m.empno group by e.mgr,m.ename);
100.
List the name,salary,comm. For those employees whose net pay is greater than
or equal
to any other employee salary of the company.
A)
select e.ename,e.sal,e.comm from emp e where
nvl2(e.comm.,e.sal+e.comm.,e.sal)
>= any (select sal from emp);
(OR)
B)
select ename,sal,comm. from emp where sal+nvl(comm.,0) >=
any
(select sal from emp);/
101.
List the emp whose sal<his manager but more than any other manager.
a)
select distinct W.empno,W.ename,W.sal
from
(select w.empno,w.ename,w.sal from emp w,emp m where
w.mgr
= m.empno and w.sal<m.sal) W,
(select
* from emp where empno in (select mgr from emp))
A
where W.sal > A.sal; (OR)
B)
select * from emp w,emp m where w.mgr = m.empno and w.sal < m.sal
and
w.sal > any (select sal from emp where empno in (select mgr from emp));
102.
List the employee names and his average salary department wise.
A) select d.deptno, round(avg(nvl2(e1.comm,
e1.sal+e1.comm, e1.sal))) avg,
e2.ename from emp e1, emp e2, dept d where
d.deptno =e1.deptno and d.deptno = e2.deptno group by d.deptno, e2.ename; (or)
B)
select d.maxsal,e.ename,e.deptno as "current sal" from emp e,
(select
avg(Sal) maxsal,deptno from emp group by deptno) d
where
e.deptno=d.deptno;
103.
Find out least 5 earners of the company.
A)
select * from emp e where 5> (select count(*) from emp where
e.sal
>sal); (or)
B)
select rownum rank,empno,ename,job,sal from (select * from
emp
order by sal asc) where rownum < 6 ; (or)
C)
select * from emp e where 5 >(select count(distinct sal) from
emp
where e.sal > sal);
104.
Find out emps whose salaries greater than salaries of their managers.
A)
select * from emp w,emp m where w.mgr = m.empno and w.sal>
m.sal;
(OR)
B)
select * from emp e ,(select * from emp where empno in (select
mgr from
emp)) a
where
e.sal >a.sal and e.mgr = a.empno
105.
List the managers who are not working under the president.
A)
select * from emp where empno in(select mgr from emp) and mgr not in
(select
empno from emp where job = 'PRESIDENT')
106.
List the records from emp whose deptno isnot in . List the Name , Salary, Comm
and Net Pay is more than any other employee.
A)
Select e.ename,e.sal,e.comm,nvl2(comm,sal+comm,sal)
NETPAY
from
emp e
where
nvl2(comm,sal+comm,sal) > any (select sal from emp
where
empno =e.empno) ;
108.
List the Enames who are retiring after the max Job period is 20Y.
A)
select ename from emp where add_months(hiredate,240) > '31-DEC-89';
B)
select ename from emp
where
add_months(hiredate,240) > to_date(’31-DEC-89’,’DD-MON-RR’);
109.
List those Emps whose Salary is odd value.
A)
select * from emp where mod(sal,2) = 1;
110.
List the emp’s whose Salary contain 3 digits.
A)
select * from emp where length (sal) = 3;
111.
List the emps who joined in the month of DEC.
A)
select * from emp where to_char(hiredate,’MON’) =’DEC’;
(OR)
B)
select * from emp where to_char(hiredate,’MON’) in (‘DEC’);
(OR)
C)
select * from emp where to_char(hiredate,’MONTH’) like
‘DEC%’;
112.
List the emps whose names contains ‘A’.
A)
select * from emp where ename like ‘%A%’;
113.
List the emps whose Deptno is available in his Salary.
A)
select * from emp where instr(sal,deptno) > 0;
114.
List the emps whose first 2 chars from Hiredate=last 2 characters of Salary.
A)
select * from emp
where
substr(hiredate,1,2) = substr(sal,length(sal)-1,length(sal));
115.
List the emps Whose 10% of Salary is equal to year of joining.
A)
select * from emp where to_char(hiredate,'YY') in (select .1*sal from emp);
116.
List first 50% of chars of Ename in Lower Case and remaining are upper Case.
A) select
lower(substr(ename,1,round(length(ename)/2)))
||substr(ename,round(length(ename)/2)+1,length(ename))
from emp ; (OR) B) select
lower(substr(ename,1,ciel(length(ename)/2)))
||
substr(ename,ciel(length(ename)/2)+1,length(ename)) from emp ;
117.
List the Dname whose No. of Emps is =to number of chars in the Dname.
A)
select * from dept d where length(dname) in (select count(*)
from emp
e where e.deptno = d.deptno ); (or)
B)
select d.dname,count(*) from emp e ,dept d where e.deptno =
d.deptno
group by d.dname having count(*) = length (d.dname);
118.
List the emps those who joined in company before 15th of the month.
A)
select * from emp where to_char(hiredate,'DD') < '15';
119.
List the Dname, no of chars of which is = no. of emp’s in any other Dept.
A)
select * from dept d where length(dname) in (select count(*)
from
emp where d.deptno <> deptno group by deptno ); (or)
B)
select * from dept where length(dname) = any (select count(*)
from emp
where d.deptno <> deptno group by deptno);
C)
select * from dept d , (select count(*) s,e.deptno "M"from emp
e
group by
e.deptno) d1
where
length(dname)=d1.s and d1.M <>d.deptno;
120.
List the emps who are working as Managers.
A) select
* from where job = ‘MANAGER’; (or)
B)
select * from emp where empno in (select mgr from emp );
121.
List THE Name of dept where highest no.of emps are working.
A)
select dname from dept where deptno in
(select
deptno from emp group by
deptno
having
count(*) in
(select
max(count(*)) from emp group by deptno) );
122.
Count the No.of emps who are working as ‘Managers’(using set option).
A)select
count(*)
from(select
* from emp minus select * from emp where job != 'MANAGER')
123.
List the emps who joined in the company on the same date.
A)
select * from emp e where hiredate in
(select
hiredate from emp where e.empno <> empno);
124.
List the details of the emps whose Grade is equal to one tenth of Sales Dept.
A)
select * from emp e,salgrade s
where
e.sal between s.losal and s.hisal and
s.grade
= 0.1* (select deptno from dept where dname = 'SALES');
125. List the name of
the dept where more than average no. of emps are working.
A)
select d.dname from dept d, emp e where e.deptno = d.deptno
group
by d.dname
having
count(*) > (select avg(count(*)) from emp group by deptno);
126.
List the Managers name who is having max no.of emps working under him.
A)select
m.ename,count(*) from emp w,emp m
where
w.mgr = m.empno
group
by m.ename
having
count(*) = (select max(count(*)) from emp group by
mgr);
(OR)
B)
select * from emp where empno = (select mgr from emp group by mgr having
count(*)
= (select max(count(*)) from emp group by mgr)) ;
127.
List the Ename and Sal is increased by 15% and expressed as no.of Dollars.
A)
select ename,to_char(1.15*sal,'$99,999') as "SAL" from emp;
(only for $ it
works)
B)
select ename,'$'||1.15*sal “SAL” from emp;
128.
Produce the output of table ‘_AND_JOB’ for Ename and Job.
A)
select ename|| job as "EMP_AND_JOB" from emp ;
129.
Produce the following output from .
EMPLOYEE
SMITH
(clerk)
ALLEN
(Salesman)
A)
select ename || ‘(‘|| lower(job)||’)’ as “EMPLOYEE” from emp;
130)
List the emps with Hire date in format .
A)
select empno,ename,sal, to_char(hiredate,'MONTH DD,YYYY') from
emp;
131)
Print a list of emp’s Listing ‘just salary’ if Salary is more than 1500, on
target if
Salary
is 1500 and ‘Below 1500’ if Salary is less than 1500.
A)
select empno,ename,sal|| ‘ SALARY’ "SAL" from emp where sal >
1500
union
select
empno,ename, sal|| ‘ON TARGET’ "SAL" from emp where sal =
1500
union
select empno,ename, sal|| ‘BELOW 1500’ "SAL" from emp where sal <
1500;
(OR)
B)select
empno,ename,sal,job,
case
when sal
= 1500 then 'ON TARGET'
when sal
< 1500 then 'BELOW 1500'
when sal
> 1500 then ' SALARY'
else
'nothing'
end
"REVISED SALARY"
from
emp;
132)
Write a query which return the day of the week for any date entered in format
‘DD-MM-YY’.
A)
select to_char(to_date('& s','dd-mm-yy'),'day') from dual ;
133)
Write a query to calculate the length of service of any employee with the
company,
use DEFINE to avoid repetitive typing of functions.
A)
DEFINE service = ((months_between(sysdate,hiredate))/12)
B)
Select empno,ename,&service from emp where ename = ‘& name’;
134)
Give a string of format ‘NN/NN’, verify that the first and last two characters
are
numbers
and that the middle character is’/’. Print the expression ‘YES’ if valid,
‘NO’ if
not valid. Use the following values to test your solution.
‘12/34’,’01/1a’,
‘99/98’.
A)
135)
Emps hired on or before 15th of any month are paid on the last Friday of that
month
those hired after 15th are paid on the first Friday of the following month.
Print a
list of emps their hire date and the first pay date. Sort on hire date.
A)
select ename,hiredate,next_day(last_day(hiredate),'FRIDAY')-7 from emp
where
to_char(hiredate,'DD') <=15
union
select
ename,hiredate,next_day(last_day(hiredate),'FRIDAY') from emp where
to_char(hiredate,'DD')
> 15;
136)
Count the no. of characters with out considering spaces for each name.
A)
select length(replace(ename,’ ‘,null)) from emp;
137)
Find out the emps who are getting decimal value in their Sal without using like
operator.
A)
select * from emp where instr(sal,’.’,1,1) > 0;
138)
List those emps whose Salary contains first four digit of their Deptno.
A) select
* from emp where instr(to_char(sal,,9999),deptno,1,1)>0 and
instr(to_char(sal,9999),deptno,1,2)>
0 ;
139)
List those Managers who are getting less than his emps Salary.
A)
select distinct m.ename,m.sal from emp w,emp m where w.mgr =
m.empno
and w.sal>m.sal;
B)
select * from emp w where sal < any ( select sal from emp where
w.empno=mgr);
C)
select * from emp w where empno in ( select mgr from emp
where
w.sal<sal);
140)
Print the details of all the emps who are sub-ordinates to Blake.
A)
select * from emp where mgr in (select empno from emp where ename =
'BLAKE');
141)
List the emps who are working as Managers using co-related sub-query.
A)
select * from emp where empno in (select mgr from emp);
142)
List the emps whose Mgr name is ‘Jones’ and also with his Manager name.
A)
select w.ename,m.ename,(select ename from emp where m.mgr = empno)
"his
MANAGER"
from
emp w,emp m where w.mgr = m.empno and m.ename = 'JONES';
(or)
B)
select e.ename,w.ename,m.ename from emp e,emp w,emp m where e.mgr
=
w.empno and w.ename = ‘JONES’ and w.mgr = m.empno;
143)
Define a variable representing the expression used to calculate on emps total
annual
remuneration use the variable in a statement, which finds all emps who
can earn
30000 a year or more.
A) Set
define on
B)
Define annual = 12*nvl2(comm.,sal+comm.,sal) (here define variable
is
a
session variable)
C)
Select * from emp where &annual > 30000;
144)
Find out how may Managers are their in the company.
A)
select count(*) from emp where job = ‘MANAGER’; (or) B) select count(*) from
emp where empno in (select mgr from emp); (or)
C)
select count(distinct m.empno) from emp w,emp m where w.mgr =
m.empno
;
145)
Find Average salary and Average total remuneration for each Job type.
Remember
Salesman earn commission.secommm
A)
select avg(sal),avg(sal+nvl(comm,0)) from emp;
146)
Check whether all the emps numbers are indeed unique.
A)
select empno,count(*) from emp group by empno;
147)
List the emps who are drawing less than 1000 Sort the output by Salary.
A)select
* from emp where sal < 1000 order by sal;
148)
List the employee Name, Job, Annual Salary, deptno, Dept name and grade who
earn 36000 a year or who are not CLERKS.
A)selecte.ename,e.job,(12*e.sal)"ANNUALSALARY",
e.deptno,d.dname,s.grade
from emp
e,dept d ,salgrade s where e.deptno = d.deptno and e.sal between
s.losal
and s.hisal
and
(((12*e.sal)>= 36000) or (e.job != 'CLERK'))
149)
Find out the Job that was filled in the first half of 1983 and same job that
was
filled
during the same period of 1984.
A)
select * from emp where (to_char(hiredate,'MM ') <= 06 and
to_char(hiredate,'YYYY')
= 1984) and job in (select job from emp where
to_char(hiredate,'MM'
) <= 06 and to_char(hiredate,'YYYY') <= 1983) ;
150)
Find out the emps who joined in the company before their Managers.
A)
select * from emp w,emp m where w.mgr = m.empno and
w.hiredate<
m.hiredate;(or)
B)
select * from emp e where hiredate < (select hiredate from emp where
empno =
e.mgr)
151)
List all the emps by name and number along with their Manager’s name and
number.
Also List KING who has no ‘Manager’.
A)
select w.empno,w.ename,m.empno,m.ename from emp w,emp m where
w.mgr=
m.empno(+);
152)
Find all the emps who earn the minimum Salary for each job wise in ascending
order.
A) select * from emp where sal in
(select
min(sal) from emp group by job)
order
by sal asc;
153)
Find out all the emps who earn highest salary in each job type. Sort in
descending
salary order.
A)
select * from emp where sal in
(select
max(sal) from emp group by job)
order
by sal desc;
154)
Find out the most recently hired emps in each Dept order by Hiredate.
A)
select * from emp e where hiredate in
(select
max(hiredate) from emp where e.deptno = deptno )
order
by hiredate;
155)
List the employee name,Salary and Deptno for each employee who earns a
salary
greater than the average for their department order by Deptno.
A)
select * from emp e
where
sal > (select avg(sal) from emp where e.deptno = deptno );
B)
select e.ename,e.sal,e.deptno from emp e,(select avg(sal) A,deptno D
from
emp
group by deptno) D1 where D1.D = e.deptno and e.sal > D1.A;
156)
List the Deptno where there are no emps.
A)
select deptno ,count(*) from emp
group
by deptno
having
count(*) = 0;
157)
List the No.of emp’s and Avg salary within each department for each job.
A)
select count(*),avg(sal),deptno,job from emp
group
by deptno,job;
158)
Find the maximum average salary drawn for each job except for ‘President’.
A)
select max(avg(sal)) from emp where job != 'PRESIDENT' group by job;
159)
Find the name and Job of the emps who earn Max salary and Commission.
A) select
* from emp where sal = (select max(sal) from emp) and comm. is
not
null;
160)
List the Name, Job and Salary of the emps who are not belonging to the
department
10 but who have the same job and Salary as the emps of .
A)
select ename,job,sal from emp where deptno != 10 and job in (select job
from emp
where deptno = 10)
and sal
in (select sal from emp where deptno = 10);
161)
List the Deptno, Name, Job, Salary and Sal+Comm of the SALESMAN who are
earning
maximum salary and commission in descending order.
A)select
deptno,name,job,sal,sal+nvl(comm.,0) from emp where job =
‘SALESMAN’
and sal in (select max(sal+nvl(comm.,0)) from emp where
comm. is
not null)
Order by
(sal +nvl(comm.,0)) desc;
162)
List the Deptno, Name, Job, Salary and Sal+Comm of the emps who earn the
second
highest earnings (sal + comm.).
A)
select deptno,ename,sal,job,sal+nvl(comm,0) from emp e where 2 = (select
count(distinct
sal+nvl(comm,0)) from emp where
(e.sal+nvl(comm.,0))<(sal+nvl(comm.,0));
163)
List the Deptno and their average salaries for dept with the average salary
less
than the
averages for all department
A)
select deptno,avg(sal) from emp group by deptno
having
avg(sal) <(select avg(Sal) from emp);
164)
List out the Names and Salaries of the emps along with their manager names
and
salaries for those emps who earn more salary than their Manager.
A)
select w.ename,w.sal,m.ename,m.sal from emp w,emp m
where
w.mgr = m.empno and w.sal > m.sal;
165)
List out the Name, Job, Salary of the emps in the department with the highest
average
salary.
A)
select * from emp where deptno in
(select
deptno from emp e
having
avg(sal) =(select max(avg(sal)) from emp group by deptno)
group
by deptno);
166)
List the empno,sal,comm. Of emps. A) select empno,sal,comm. from emp;
A)
167)
List the details of the emps in the ascending order of the sal.
A)
select * from emp order by sal asc;
168) List the dept in the ascending order of the job and the desc order of the emps
print
empno, ename.
A)
select * from emp e order by e.job asc,e.empno desc ;
169)
Display the unique dept of the emps.
A)select
* from dept where deptno in (select unique deptno from emp);
170)
Display the unique dept with jobs.
A)
select unique deptno ,job from emp ;
171)
Display the details of the blake.
A)
select * from emp where ename = ‘BLAKE’;
172)
List all the clerks.
A)
select * from emp where job = ‘CLERK’;
173)
list all the employees joined on 1st may
81.
A)
select * from emp where hiredate = ’01-MAY-81’;
174)
List the empno,ename,sal,deptno of the emps in the ascending order of
salary.
A)
select e.empno,e.ename,e.sal,e.deptno from emp where e.deptno = 10
order by
e.sal asc;
175)
List the emps whose salaries are less than 3500.
A)
select * from emp where sal <3500;
176)
List the empno,ename,sal of all the emp joined before 1 apr 81.
A)
select e.empno ,e.ename .e.sal from emp where hiredate <’01-APR-81’;
177)
List the emp whose annual sal is <25000 in the asc order of the salaries.
A)
select * from emp where (12*sal) < 25000 order by sal asc;
178)
List the empno,ename,annsal,dailysal of all the salesmen in the asc ann
sal
A)
select e.empno,e.ename ,12*sal "ANN SAL" , (12*sal)/365 "DAILY
SAL"
from emp
e where e.job = 'SALESMAN'
order by
"ANN SAL" asc ;
179)
List the empno,ename,hiredate,current date & exp in the ascending order of
the exp.
A)
select empno,ename,hiredate,(select sysdate from
dual),((months_between(sysdate,hiredate))/12)
EXP
from
emp
order
by EXP asc;
180)
List the emps whose exp is more than 10 years.
A)
select * from emp where ((months_between(sysdate,hiredate))/12) > 10;
181)
List the empno,ename,sal,TA30%,DA 40%,HRA
50%,GROSS,LIC,PF,net,deduction,net
allow and net sal in the ascending order
of the
net salary.
A)
182)
List the emps who are working as managers.
A)
select * from emp where job = ‘MANAGER’;
183)
List the emps who are either clerks or managers.
A)
select * from emp where job in (‘CLERK’,’MANAGER’);
184)
List the emps who have joined on the following dates 1 may 81,,30
dec 81
A)
select * from emp where to_char(hiredate,’DD-MON-YY’) in
(’01-MAY-81’,’17-NOV-81’,’30-DEC-81’);
185)
List the emps who have joined in the year 1981.
A)
select * from emp where to_char(hiredate,’YYYY’) = ‘1981’;
186)
List the emps whose annual sal ranging from 23000 to 40000.
A)
select * from emp where (12* sal) between 23000 and 40000;
187)
List the emps working under the mgrs 7369,7890,7654,7900.
A)
select * from emp where mgr in ( 7369,7890,7654,7900);
188)
List the emps who joined in the second half of 82.
A)select
* from emp where hiredate between ’01-JUL-82’ and ’31-DEC-82’;
189)
List all the 4char emps.
A)
select * from emp where length (ename) = 4;
190)
List the emp names starting with ‘M’ with 5 chars.
A)
select * from emp where ename like ‘M%’ and length (ename) = 5;
191)
List the emps end with ‘H’ all together 5 chars.
A)
select * from emp where ename like ‘%H’ and length (ename) = 5;
192) List
names start with ‘M’.
A)
select * from emp where ename like ‘M%’;
193)
List the emps who joined in the year 81.
A)
select * from emp where to_char(hiredate,’YY’) = ‘81’;
194)
List the emps whose sal is ending with 00.
A)
select * from where sal like ‘’;
195)
List the emp who joined in the month of JAN.
A)
select * from emp where to_char(hiredate,’MON’) = ‘JAN’; (OR)
B)
select * from emp where to_char (hiredate,’MM’) = 1;
196) Who
joined in the month having char ‘a’.
A)
select * from emp where to_char (hiredate,’MONTH’) like’%A%’; (OR)
B)
select * from emp where instr(to_char(hiredate,’MONTH’),’A’) >0;
197) Who
joined in the month having second char ‘a’
A)
select * from emp where to_char(hiredate,’MON’) like ‘_A%’; (OR)
B)
select * from emp where instr(to_char(hiredate,’MON’),’A’) = 2;
198)
List the emps whose salary is 4 digit number.
A)
select * from emp where length (sal) = 4;(OR)
B)
select * from emp where sal between 999 and 9999;
199)
List the emp who joined in 80’s.
A) select
* from emp where to_char(hiredate,’YY’) between ‘80’ and ’89’;
(OR)
B) select * from emp where to_char(hiredate,’YY’) >= ‘80’ and
to_char(hiredate,’YY’)
< ‘90’;
200)
List the emp who are clerks who have exp more than 8ys.
A)
select * from emp where job = ‘CLERK’ and
(months_between(sysdate,hiredate)
/12) > 8;
201)
List the mgrs of or 20.
A)
select * from emp where job = ‘MANAGER’ and (deptno = 10 or deptno
=20);
202)
List the emps joined in jan with salary ranging from 1500 to 4000.
A)
select * from emp where to_char(hiredate,’MON’) = ‘JAN’ and sal
between
1500 and 4000;
203)
List the unique jobs of and 30 in desc order.
A)
select distinct job from emp where deptno in (20,30) order by job desc;
204)
List the emps along with exp of those working under the mgr whose number is
starting
with 7 but should not have a 9 joined before 1983.
A)
select * from emp where (mgr like '7%' and mgr not like '%9%')
and
to_char(hiredate,'YY') < '83';
205)
List the emps who are working as either mgr or analyst with the salary ranging
from
2000 to 5000 and with out comm.
A)
select * from emp where (job in (‘MANAGER’ ,’ANALYST’) ) and sal
between
2000 and 5000 and comm is null;
206)
List the empno,ename,sal,job of the emps with /ann sal <34000 but receiving
some
comm. Which should not be>sal and desg should be sales man working
for .
A)
select empno,ename,sal,job from emp where
12*(sal+nvl(comm,0))
< 34000 and comm is not null and comm<sal and job =
'SALESMAN'
and deptno = 30;
207)
List the emps who are working for or 20 with desgs as clerk or analyst
with a
sal is either 3 or 4 digits with an exp>8ys but does not belong to mons of
mar,apr,sep
and working for mgrs &no is not ending with 88 and 56.
A)
select * from emp where
deptno
in (10,20) and
job in
('CLERK','ANALYST') and (length(sal) in (3,4)) and
((months_between(sysdate,hiredate))/12)>
8 and
to_char(hiredate,'MON')
not in ('MAR','SEP','APR') and
(mgr not
like '%88' and mgr not like '%56');
208)
List the empno,ename,sal,job,deptno&exp of all the emps belongs to or
20 with
an exp y working under the same mgr with out comm. With a
job not
ending irrespective of the position with comm.>200 with exp>=7y and
sal<2500
but not belongs to the month sep or nov working under the mgr whose
no is
not having digits either 9 or 0 in the asc dept& desc dept
A)
209)
List the details of the emps working at .
A)
select * from emp where deptno in (select deptno from dept where dept.loc =
‘’);
210)
List the empno,ename,deptno,loc of all the emps.
A)
select e.empno,e.ename,e.deptno,d.loc from emp e ,dept d
where
e.deptno = d.deptno ;
211)
List the empno,ename,loc,dname of all the depts.,10 and 20.
A)
select e.empno,e.ename,e.deptno,d.loc,d.dname from emp e ,dept d
where
e.deptno = d.deptno and e.deptno in (10,20);
212)
List the empno, ename, sal, loc of the emps working at with an
exp>6ys.
A)
select e.empno,e.ename,e.deptno,e.sal,d.loc from emp e ,dept d
where
e.deptno = d.deptno and d.loc in ('CHICAGO','')
and
(months_between(sysdate,hiredate)/12)> 6 ;
213)
List the emps along with loc of those who belongs to ,newyork with sal
ranging
from 2000 to 5000 joined in 81.
A)
select e.empno,e.ename,e.deptno,e.sal,d.loc from emp e ,dept d
where
e.deptno = d.deptno and d.loc in ('','')
and
to_char(e.hiredate,'YY') = '81' and e.sal between 2000 and
5000;
214)
List the empno,ename,sal,grade of all emps.
A) select e.empno,e.ename,e.sal,s.grade from emp e
,salgrade s
where
e.sal between s.losal and s.hisal ;
215)
List the grade 2 and 3 emp of .
A)
select * from emp where empno in
(select
empno from emp e,salgrade s where e.sal between s.losal
and
s.hisal
and s.grade in (2,3));
216)
List the emps with loc and grade of accounting dept or the locs or with
the grades 3 to 5 &exp >6y
A)
select e.deptno,e.empno,e.ename,e.sal,d.dname,d.loc,s.grade from emp
e,salgrade
s,dept d
wheree.deptno
= d.deptno and e.sal between s.losal and s.hisal
and
s.grade in (3,5)
and
((months_between(sysdate,hiredate))/12) > 6
and
( d.dname = 'ACCOUNTING' or D.loc in ('DALLAS',''))
217)
List the grades 3 emps of research and operations depts.. joined after 1987 and
whose
names should not be either miller or allen.
A)
select e.ename from emp e ,dept d,salgrade s
where
e.deptno = d.deptno and d.dname in
('OPERATIONS','RESEARCH')
and e.sal between s.losal and s.hisal
and
e.ename not in ('MILLER','ALLEN')
and
to_char(hiredate,'YYYY') >1987;
218)
List the emps whose job is same as smith.
A)
select * from emp where job = (select job from emp where ename =
'SMITH');
219)
List the emps who are senior to mi ler.
A)
select * from emp where
hiredate <(select hiredate from emp where
ename =
‘MILLER’);
220)
List the emps whose job is same as either allen or sal>allen.
A)
select * from emp
where
job = (select job from emp where ename = 'ALLEN')
or
sal > (select sal from emp where ename = 'ALLEN');
221)
List the emps who are senior to their own manager.
A)
select * from emp w,emp m where w.mgr = m.empno and
w.hiredate
< m.hiredate;
222)
List the emps whose sal greater than blakes sal.
A)
select * from emp
where
sal>(select sal from emp where ename = ‘BLAKE’);
223)
List the emps whose sal>allen sal.
A)
select * from emp where deptno = 10 and
sal
> (select sal from emp where ename = 'ALLEN');
224)
List the mgrs who are senior to king and who are junior to smith.
A)select
* from emp where empno
in (select
mgr from emp
where
hiredate<(select hiredate from emp where ename = 'KING' )
and
hiredate > (select hiredate from emp where ename = 'SMITH')) and mgr
is not null;
225)
List the empno,ename,loc,sal,dname,loc of the all the emps belonging to king
dept.
A)
select e.empno,e.ename,d.loc,e.sal,d.dname from emp e,dept d
where
e.deptno=d.deptno and e.deptno in
(select
deptno from emp where ename = 'KING'and emp.empno <>
e.empno);
226)
List the emps whose salgrade are greater than the grade of miller.
A)
select * from emp e,salgrade s
where
e.sal between s.losal and s.hisal and s.grade >
(select
s.grade from emp e,salgrade s where e.sal between s.losal and s.hisal
and
e.ename = 'MILLER') ;
227)
List the emps who are belonging dallas or Chicago with the grade same as
adamsor
exp more than smith.
A)
select * from emp e ,dept d,salgrade s
where
e.deptno= d.deptno and d.loc in ('DALLAS','')
and
e.sal between s.losal and s.hisal
and
(s.grade in (select s.grade from emp e,salgrade s where e.sal
between
s.losal and s.hisal and e.ename = '')
or
months_between
(sysdate,hiredate)
> (select months_between(sysdate,hiredate) from emp where ename = 'SMITH'))
;
228)
List the emps whose sal is same as ford or blake.
A)
select * from emp where sal in (select sal from emp e where e.ename in
('','BLAKE')and
emp.empno <> e.empno);
229)
List the emps whose sal is same as any one of the following.
A)
select * from emp where sal in
(select
sal from emp e where emp.empno <> e.empno);
230) Sal
of any clerk of emp1 table.
A)
select * from emp where job = ‘CLERK’;
231) Any
emp of emp2 joined before 82.
A)
select * from emp where to_char(hiredate,'YYYY') < 1982;
232) The
total remuneration (sal+comm.) of all sales person of Sales dept belonging
to emp3
table.
A) select * from emp e
where
(sal+nvl(comm,0)) in
(select
sal+nvl(comm,0) from emp e,dept d where e.deptno=d.deptno
and
d.dname = 'SALES'and e.job = 'SALESMAN');
233) Any
Grade 4 emps Sal of emp 4 table.
A)
select * from emp4 e,salgrade s where e.sal between s.losal and s.hisal and
s.grade
= 4;
234) Any
emp Sal of emp5 table.
A)
select * from emp5;
235)
List the highest paid emp.
A)
select * from emp where sal in (select max(sal) from emp);
236)
List the details of most recently hired emp of .
A)
select * from emp where hiredate in
(select
max(hiredate) from emp where deptno = 30);
237)
List the highest paid emp of joined before the most recently hired emp
of grade
2.
A)
select * from emp
where
sal = ( select max(sal) from emp e,dept d where e.deptno =
d.deptno
and d.loc = ‘’ and
hiredate
<(select max(hiredate) from emp e,salgrade
s
where
e.sal between s.losal and s.hisal and s.grade = 2))
238)
List the highest paid emp working under king.
A)select
* from emp where sal in
(select
max(sal) from emp where mgr in
(select
empno from emp where ename = 'KING'));
239) Display those employees who are working as manager?
select e2.ename from emp e1,e2 where e1.mgr=e2.empno and e2.empno is not null
240) Count th number of employees who are working as managers (Using set opetrator)?
SELECT d.dname
FROM dept d
WHERE LENGTH (d.dname) IN (SELECT COUNT (*)
FROM emp e
WHERE e.deptno != d.deptno
GROUP BY e.deptno)
241) Display the name of the dept those employees who joined the company on the same date?
select a.ename,b.ename from emp a,emp b where a.hiredate=b.hiredate and a.empno!=b.empno
242) Display those employees whose grade is equal to any number of sal but not equal to first number of salary?
SELECT ename, sal, grade, SUBSTR (sal, grade, 1)
FROM emp, salgrade
WHERE grade != SUBSTR (sal, 1, 1)
AND grade = SUBSTR (sal, grade, 1)
AND sal BETWEEN losal AND hisal
243) Count the no of employees working as manager using set operation?
SELECT COUNT (empno)
FROM emp
WHERE empno IN (SELECT a.empno
FROM emp a
INTERSECT
SELECT b.mgr
FROM emp b)
244) Display the name of employees who joined the company on the same date?
select a.ename,b.ename from emp a,emp b where a.hiredate=b.hiredate and a.empno!=b.empno;
245) Display the manager who is having maximum number of employees working under him?
SELECT e2.ename, COUNT (*)
FROM emp e1, e2
WHERE e1.mgr = e2.empno
GROUP BY e2.ename
HAVING COUNT (*) = (SELECT MAX (COUNT (*))
FROM emp e1, e2
WHERE e1.mgr = e2.empno
GROUP BY e2.ename)
246) List out the employee name and salary increased by 15% and express as whole number of Dollars?
select ename,sal,lpad(translate(sal,sal,((sal +(sal*0.15))/50)),5,'$') from emp
247) Produce the output of the emptable "EMPLOYEE_AND JOB" for ename and job ?
Ans: select ename"EMPLOYEE_AND",job"JOB" FROM EMP;
248) List of employees with hiredate in the format of 'June 4 1988'?
Ans: select ename,to_char(hiredate,'Month dd yyyy') from emp;
249) print list of employees displaying 'Just salary' if more than 1500 if exactly 1500 display 'on taget' if less than 1500 display below 1500?
Ans:
SELECT ename, sal,
(CASE
WHEN sal < 1500
THEN 'Below_Target'
WHEN sal = 1500
THEN 'On_Target'
WHEN sal > 1500
THEN 'Above_Target'
ELSE 'kkkkk'
END
)
FROM emp
250) Which query to calculate the length of time any employee has been with the company
Ans: select hiredate, to_char (hiredate,' HH:MI:SS') FROM emp
251) Employes hire on OR Before 15th of any month are paid on the last friday of that month those hired after 15th are paid the last friday of th following month .print a list of employees .their hiredate and first pay date sort those who se salary contains first digit of their deptno?
Ans:
SELECT ename, hiredate, LAST_DAY (NEXT_DAY (hiredate, 'Friday')),
(CASE
WHEN TO_CHAR (hiredate, 'dd') <= ('15')
THEN LAST_DAY (NEXT_DAY (hiredate, 'Friday'))
WHEN TO_CHAR (hiredate, 'dd') > ('15')
THEN LAST_DAY (NEXT_DAY (ADD_MONTHS (hiredate, 1), 'Friday'))
END
)
FROM emp
252) Display those managers who are getting less than his employees salary?
Ans: select a.empno, a.ename, a.sal, b.sal, b.empno, b.ename from emp a, emp b where a.mgr=b.empno and a.sal>b.sal
253) Print the details of employees who are subordinates to BLAKE?
Ans: select a.empno,a.ename ,b.ename from emp a, emp b where a.mgr=b.empno and b.ename='BLAKE'
239) Display those employees who are working as manager?
select e2.ename from emp e1,e2 where e1.mgr=e2.empno and e2.empno is not null
240) Count th number of employees who are working as managers (Using set opetrator)?
SELECT d.dname
FROM dept d
WHERE LENGTH (d.dname) IN (SELECT COUNT (*)
FROM emp e
WHERE e.deptno != d.deptno
GROUP BY e.deptno)
241) Display the name of the dept those employees who joined the company on the same date?
select a.ename,b.ename from emp a,emp b where a.hiredate=b.hiredate and a.empno!=b.empno
242) Display those employees whose grade is equal to any number of sal but not equal to first number of salary?
SELECT ename, sal, grade, SUBSTR (sal, grade, 1)
FROM emp, salgrade
WHERE grade != SUBSTR (sal, 1, 1)
AND grade = SUBSTR (sal, grade, 1)
AND sal BETWEEN losal AND hisal
243) Count the no of employees working as manager using set operation?
SELECT COUNT (empno)
FROM emp
WHERE empno IN (SELECT a.empno
FROM emp a
INTERSECT
SELECT b.mgr
FROM emp b)
244) Display the name of employees who joined the company on the same date?
select a.ename,b.ename from emp a,emp b where a.hiredate=b.hiredate and a.empno!=b.empno;
245) Display the manager who is having maximum number of employees working under him?
SELECT e2.ename, COUNT (*)
FROM emp e1, e2
WHERE e1.mgr = e2.empno
GROUP BY e2.ename
HAVING COUNT (*) = (SELECT MAX (COUNT (*))
FROM emp e1, e2
WHERE e1.mgr = e2.empno
GROUP BY e2.ename)
246) List out the employee name and salary increased by 15% and express as whole number of Dollars?
select ename,sal,lpad(translate(sal,sal,((sal +(sal*0.15))/50)),5,'$') from emp
247) Produce the output of the emptable "EMPLOYEE_AND JOB" for ename and job ?
Ans: select ename"EMPLOYEE_AND",job"JOB" FROM EMP;
248) List of employees with hiredate in the format of 'June 4 1988'?
Ans: select ename,to_char(hiredate,'Month dd yyyy') from emp;
249) print list of employees displaying 'Just salary' if more than 1500 if exactly 1500 display 'on taget' if less than 1500 display below 1500?
Ans:
SELECT ename, sal,
(CASE
WHEN sal < 1500
THEN 'Below_Target'
WHEN sal = 1500
THEN 'On_Target'
WHEN sal > 1500
THEN 'Above_Target'
ELSE 'kkkkk'
END
)
FROM emp
250) Which query to calculate the length of time any employee has been with the company
Ans: select hiredate, to_char (hiredate,' HH:MI:SS') FROM emp
251) Employes hire on OR Before 15th of any month are paid on the last friday of that month those hired after 15th are paid the last friday of th following month .print a list of employees .their hiredate and first pay date sort those who se salary contains first digit of their deptno?
Ans:
SELECT ename, hiredate, LAST_DAY (NEXT_DAY (hiredate, 'Friday')),
(CASE
WHEN TO_CHAR (hiredate, 'dd') <= ('15')
THEN LAST_DAY (NEXT_DAY (hiredate, 'Friday'))
WHEN TO_CHAR (hiredate, 'dd') > ('15')
THEN LAST_DAY (NEXT_DAY (ADD_MONTHS (hiredate, 1), 'Friday'))
END
)
FROM emp
252) Display those managers who are getting less than his employees salary?
Ans: select a.empno, a.ename, a.sal, b.sal, b.empno, b.ename from emp a, emp b where a.mgr=b.empno and a.sal>b.sal
253) Print the details of employees who are subordinates to BLAKE?
Ans: select a.empno,a.ename ,b.ename from emp a, emp b where a.mgr=b.empno and b.ename='BLAKE'
*****************************************************END**********************************
No comments:
Post a Comment