Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

SQL Exerice

The document describes various SQL statements used in Oracle including CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, UPDATE, DELETE, and SELECT. It provides the syntax and examples for each statement. CREATE TABLE is used to create tables with columns and constraints. ALTER TABLE modifies, renames, or drops columns. DROP TABLE removes tables. INSERT adds data, UPDATE changes data, and DELETE removes data. SELECT retrieves data with optional clauses like WHERE, GROUP BY, ORDER BY.

Uploaded by

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

SQL Exerice

The document describes various SQL statements used in Oracle including CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, UPDATE, DELETE, and SELECT. It provides the syntax and examples for each statement. CREATE TABLE is used to create tables with columns and constraints. ALTER TABLE modifies, renames, or drops columns. DROP TABLE removes tables. INSERT adds data, UPDATE changes data, and DELETE removes data. SELECT retrieves data with optional clauses like WHERE, GROUP BY, ORDER BY.

Uploaded by

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

1.

CREATE TABLE Statement


Description : The Oracle CREATE TABLE statement allows you to create and define a table.

Syntax : The syntax for the Oracle CREATE TABLE statement is:

CREATE TABLE table_name


(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
);
Where : table_name is the name of the table that you wish to create.
column1, column2 are the columns that you wish to create in the table and each column must have a
datatype.

Create Table Example1 :

CREATE TABLE customers


( customer_id number(10) not null,
customer_name varchar2(50) not null,
city varchar2(50),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);

Create Table Example 2 :

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

CREATE TABLE table_name


( column1 datatype null/not null,
column2 datatype null/not null,
...

CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...


column_n) );
*****************************************************************
Create Table Example 3 :

CREATE TABLE supplier


(
supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
**********************************************************
Create Table Example 4 :

CREATE TABLE supplier


(
supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name)
);

**********************************************************
Create Table Example 5 :

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id)
);
**********************************************************
Create Table Example 6 :

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
CONSTRAINT fk_supplier_comp FOREIGN KEY (supplier_id, supplier_name)
REFERENCES supplier(supplier_id, supplier_name) );
2. ALTER TABLE Statement
Description : The Oracle ALTER TABLE statement is used to add, modify, or drop/delete columns
in a table.

2.1 Add column in table


ALTER TABLE table_name
ADD column_name column-definition;
Alter Table Example 1 :

ALTER TABLE customers


ADD customer_name varchar2(45);

Alter Table Example 2 :

ALTER TABLE customers


ADD (customer_name varchar2(45),
city varchar2(40));

This Oracle ALTER TABLE example will add two columns, customer_name as a varchar2(45) field and
city as a varchar2(40) field to the customers table.

2.2 Modify column in table


ALTER TABLE table_name
MODIFY column_name column_type;
Alter Table Example 3 :

ALTER TABLE customers MODIFY customer_name varchar2(100) not null;

This Oracle ALTER TABLE example will modify the column called customer_name to be a data type of
varchar2(100) and force the column to not allow null values.

**********************************************************
Alter Table Example 4 :

ALTER TABLE customers


MODIFY (customer_name varchar2(100) not null, city varchar2(75));

This Oracle ALTER TABLE example will modify both the customer_name and city columns.

2.3 Drop column in table


ALTER TABLE table_name
DROP COLUMN column_name;
Alter Table Example 5 :

ALTER TABLE customers DROP COLUMN customer_name;


**********************************************************
Alter Table Example 5 :

ALTER TABLE table_name RENAME COLUMN old_name to new_name;

2.4 Rename table


ALTER TABLE table_name

RENAME TO new_table_name;

Alter Table Example 5 :

ALTER TABLE customers RENAME TO contacts;


3. Create Primary Key - Using ALTER TABLE statement
Description : You can create a primary key in Oracle with the ALTER TABLE statement.

Syntax :

ALTER TABLE table_name


ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...
column_n);

Alter primary key Example 1:

ALTER TABLE supplier


ADD CONSTRAINT supplier_pk PRIMARY KEY (supplier_id);

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

**********************************************************

Alter primary key Example 2:

ALTER TABLE supplier

DROP CONSTRAINT supplier_pk;

**********************************************************

Alter foreign key Example 3:

ALTER TABLE products

ADD CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id);


4. DROP TABLE Statement

Description :The Oracle DROP TABLE statement allows you to remove or delete a
table from the Oracle database.

DROP [schema_name].TABLE table_name

[ CASCADE CONSTRAINTS ];

Where : schema_name is the name of the schema that owns the table.
table_name is the name of the table to remove from the Oracle database.
CASCADE CONSTRAINTS is optional. If specified, all referential integrity constraints will be dropped as
well.

Drop table Example 1:

DROP TABLE customers;


5. INSERT Statement

Description :The Oracle INSERT statement is used to insert a single record or


multiple records into a table in Oracle.

INSERT INTO table (column1, column2, ... )

VALUES (expression1, expression2, ... );

Insert Example 1:

INSERT INTO suppliers (supplier_id, supplier_name)

VALUES (5000, 'Apple');


6. UPDATE Statement

Description : The Oracle UPDATE statement is used to update existing records in a


table in an Oracle database.

UPDATE table
SET column1 = expression1,
column2 = expression2,
...
WHERE conditions;

Where : column1, column2 are the columns that you wish to update.

Update Example 1:

UPDATE customers
SET last_name = 'Anderson'
WHERE customer_id = 5000;
**********************************************************
Update Example 2:

UPDATE customers
SET state = 'California',
customer_rep = 32
WHERE customer_id > 100;
7. DELETE Statement
Description :The Oracle DELETE statement is used to delete a single record or
multiple records from a table in Oracle.

DELETE FROM table


WHERE conditions;

Where : table is the table that you wish to delete records from and conditions are
conditions that must be met for the records to be deleted.

Delete example 1:

DELETE FROM customers


WHERE last_name = 'Smith';
**********************************************************
Delete example 2:

DELETE FROM customers


WHERE last_name = 'Anderson'
AND customer_id > 25;
**********************************************************
Delete example 3:

DELETE FROM contacts


WHERE contact_id >= 5000
AND contact_id < 6000.
**********************************************************
Delete example 4:

DELETE FROM contacts


WHERE contact_id BETWEEN 5000 AND 5999;
8. SELECT Statement
Description :The Oracle SELECT statement is used to retrieve records from one or
more tables in an Oracle database.

SELECT expressions
FROM tables
WHERE conditions;

Where : expressions are the columns or calculations that you wish to retrieve. Tables are the tables
that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
conditions are conditions that must be met for the records to be selected.

Select Example 1 :

SELECT *
FROM contacts
WHERE last_name = 'Smith'
AND contact_id >= 1000
AND contact_id <= 2000;

**********************************************************
Select Example 2 :

SELECT *
FROM contacts
WHERE last_name = 'Smith'
AND contact_id BETWEEN 1000 AND 2000;

SELECT COUNT(*) AS "Number of employees"


FROM employees
WHERE salary > 75000;

**********************************************************
Select Example 3 :

SELECT home_id, home_type, bathrooms


FROM homes
WHERE home_id < 500
AND home_type = 'two-storey'
ORDER BY home_type ASC, bathrooms DESC;
**********************************************************
Select Example 4 :
SELECT *
FROM homes
WHERE bathrooms >= 2
ORDER BY home_type ASC;

8.1 GROUP BY Clause


Description The Oracle GROUP BY Clause is used in a SELECT statement to collect
data across multiple records and group the results by one or more columns.

SELECT expression1, expression2, ... expression_n,


aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;

Where : expression1, expression2, ... expression_n are expressions that are not encapsulated within
an aggregate function and must be included in the GROUP BY Clause. Aaggregate_function can be
a function such as SUM, COUNT, MIN, MAX, or AVG functions. tables are the tables that you
wish to retrieve records from. There must be at least one table listed in the FROM clause.
conditions are conditions that must be met for the records to be selected.

Select Example 5 :

SELECT product, SUM(sale) AS "Total sales"


FROM order_details
GROUP BY product;

**********************************************************
Select Example 6 :

SELECT category, COUNT(*) AS "Number of suppliers"


FROM suppliers
WHERE available_products > 45
GROUP BY category;

**********************************************************
Select Example 7 :

SELECT department, MIN(salary) AS "Lowest salary"


FROM employees
GROUP BY department;

**********************************************************
Select Example 8 :

SELECT department, MAX(salary) AS "Highest salary"


FROM employees
GROUP BY department;

8.2 HAVING Clause


Description :The Oracle HAVING Clause is used in combination with the GROUP BY Clause to
restrict the groups of returned rows to only those whose the condition is TRUE.

SELECT expression1, expression2, ... expression_n,

aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n
HAVING condition;

**********************************************************
Select Example 8 :

SELECT department, SUM(sales) AS "Total sales"


FROM order_details
GROUP BY department
HAVING SUM(sales) > 25000;
**********************************************************
Select Example 9 :

SELECT department, MIN(salary) AS "Lowest salary"


FROM employees
GROUP BY department
HAVING MIN(salary) < 42000;
**********************************************************
Select Example 10 :

SELECT department, MAX(salary) AS "Highest salary"


FROM employees
GROUP BY department
HAVING MAX(salary) > 45000;
8.3 IN Condition
Description :The Oracle IN condition is used to help reduce the need to use multiple
OR conditions in a SELECT, INSERT, UPDATE, or DELETE statement.

expression IN (value1, value2, .... value_n);


Select Example 11 :

SELECT *
FROM customers
WHERE customer_name IN ('IBM', 'Hewlett Packard', 'Microsoft');

**********************************************************
Select Example 11 :

FROM customers
WHERE customer_name = 'IBM'
OR customer_name = 'Hewlett Packard'
OR customer_name = 'Microsoft';

**********************************************************
Select Example 12 :

SELECT *
FROM orders
WHERE order_id IN (10000, 10001, 10003, 10005);

SELECT *
FROM orders
WHERE order_id = 10000
OR order_id = 10001
OR order_id = 10003
OR order_id = 10005;

**********************************************************
Select Example 13 :

SELECT *
FROM customers
WHERE customer_name NOT IN ( 'IBM', 'Hewlett Packard', 'Microsoft');

**********************************************************
8.4 Subqueries

SELECT *
FROM all_tables tabs
WHERE tabs.table_name IN (SELECT cols.table_name
FROM all_tab_columns cols
WHERE cols.column_name = 'SUPPLIER_ID');

SELECT suppliers.name, subquery1.total_amt


FROM suppliers,
(SELECT supplier_id, SUM(orders.amount) AS total_amt
FROM orders
GROUP BY supplier_id) subquery1
WHERE subquery1.supplier_id = suppliers.supplier_id;

**********************************************************
SQL ORDER BY

The ORDER BY keyword is used to sort the result-set by one or more columns. The ORDER
BY keyword sorts the records in ascending order by default. To sort the records in a
descending order, you can use the DESC keyword.

SELECT column_name, column_name


FROM table_name
ORDER BY column_name ASC|DESC, column_name ASC|DESC;

SELECT * FROM Customers


ORDER BY Country;

SELECT * FROM Customers


ORDER BY Country DESC;

SELECT * FROM Customers


ORDER BY Country, CustomerName;

SELECT * FROM Customers


ORDER BY Country ASC, CustomerName DESC;
9. SQL INNER JOIN
The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns in both tables.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate


FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
SQL LEFT JOIN
The LEFT JOIN keyword returns all rows from the left table with the matching rows in the
right table. The result is NULL in the right side when there is no match.

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;

or:

SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SQL RIGHT JOIN
The RIGHT JOIN keyword returns all rows from the right table with the matching rows in
the left table. The result is NULL in the left side when there is no match.

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;

or:

SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;

SELECT Orders.OrderID, Employees.FirstName


FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;
SQL FULL OUTER JOIN
The FULL OUTER JOIN keyword returns all rows from the left table and from the right
table.

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SQL COUNT() Function

The COUNT() function returns the number of rows that matches a specified criteria. The
COUNT(column_name) function returns the number of values (NULL values will not be
counted) of the specified column:
SELECT COUNT(column_name) FROM table_name;

The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name;

The COUNT(DISTINCT column_name) function returns the number of distinct values of


the specified column:

SELECT COUNT(DISTINCT column_name) FROM table_name;

SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders


WHERE CustomerID=7;

SELECT COUNT(*) AS NumberOfOrders FROM Orders;

SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomers FROM


Orders;
SQL NULL Functions
Oracle does not have an ISNULL() function. However, we can use the NVL() function to
achieve the same result:

SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)
FROM Products

SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))
FROM Products

You might also like