SQL-Advanced Queries
SQL-Advanced Queries
CONTENTS
CREATE TABLE query
NOT NULL constraint
UNIQUE constraint
PRIMARY KEY constraint
FOREIGN KEY constraint
Deleting constraints
ALTER TABLE query
DROP TABLE
VIEWS – creating/updating/dropping
UNION and UNION ALL
INTERSECT
MINUS
NATURAL JOIN
JOIN/INNER JOIN
LEFT OUTER JOIN & RIGHT OUTER JOIN
• APPENDIX A,B,C
CREATE TABLE
CREATE TABLE table_name
(column_name1 data_type,
column_name2 data_type,..)
Write a query to create table students with the fields
Student_id,First_name,Last_name,marks obtained,Grade,Class,date of
birth and thus know about the data types.
CREATE TABLE From Another Table
Copying all columns from another table:
CREATE TABLE new_table_name
AS (SELECT * FROM old_table);
Copying selected columns from another table:
CREATE TABLE new_table_name
AS (SELECT * FROM old_table where condition);
Write a query to create table stud with the fields Student_id, First_name,
Last_name,date of birth of students table where class > 5
write another query to create a table stud1 with all the fields of students table
Copying selected columns from multiple tables:
CREATE TABLE dept AS
(SELECT e.Emp_ID,e.First_name,e.Last_name,d.Dept_ID,d.Salary
FROM employees e,departments d WHERE e.Emp_ID = d.Emp_ID);
CONSTRAINTS
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created, with the CREATE
TABLE statement or after the table is created ,with the ALTER TABLE
statement. Constraints can also be defined in column level or table-level.
Note: For Alter table, only future rows will be affected
TYPES:
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
NOT NULL CONSTRAINT
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. You
cannot insert a new record, or update a record without adding a value to this
field.
The following SQL enforces the "P_Id" column and the “First_Name" column
to not accept NULL values: (column level)
CREATE TABLE Persons
(P_Id number(10) NOT NULL,
LastName varchar(255) ,
FirstName varchar(255) NOT NULL,
Address varchar(255),
City varchar(255) )
UNIQUE CONSTRAINT
The UNIQUE constraint uniquely identifies each record in a database table.
It can be defined by table level and column level
It can contain NULL values
Column Level:
CREATE TABLE Persons
(P_Id number(10) UNIQUE,
LastName varchar(255) ,
FirstName varchar(255) )
Table-level:
CREATE TABLE Persons
(P_Id number(10),
LastName varchar(255) ,
FirstName varchar(255)
CONSTRAINT unique_P_ID UNIQUE(P_Id) )
UNIQUE CONSTRAINT
DROP TABLE
DROP TABLE table_name;
Example:
DROP TABLE employees;
It cannot be rolled back as it is a DDL statement.
VIEWS
Creating / Updating View
CREATE OR REPLACE VIEW emp1 AS
(SELECT e.Emp_ID,e.First_name,e.Last_name,d.Dept_ID,d.Salary
FROM employees e,departments d
WHERE e.Emp_ID = d.Emp_ID AND d.Salary >= 40000);