0% found this document useful (0 votes)
19 views

Database

The document provides information about various SQL clauses and functions including: 1) SQL constraints like NOT NULL, UNIQUE, PRIMARY KEY which specify rules for data in tables. Examples are given of creating constraints on CREATE TABLE and ALTER TABLE. 2) SQL functions like DEFAULT, DISTINCT, BETWEEN, IN, LIKE are described along with examples. 3) Examples are shown of SELECT queries with WHERE, ORDER BY, TOP clauses to filter and sort results. Operations on tables like CREATE, INSERT, UPDATE, ALTER are also demonstrated.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Database

The document provides information about various SQL clauses and functions including: 1) SQL constraints like NOT NULL, UNIQUE, PRIMARY KEY which specify rules for data in tables. Examples are given of creating constraints on CREATE TABLE and ALTER TABLE. 2) SQL functions like DEFAULT, DISTINCT, BETWEEN, IN, LIKE are described along with examples. 3) Examples are shown of SELECT queries with WHERE, ORDER BY, TOP clauses to filter and sort results. Operations on tables like CREATE, INSERT, UPDATE, ALTER are also demonstrated.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

23 December 2022 09:13 AM

New Section 1 Page 1


New Section 1 Page 2
New Section 1 Page 3
ALTER TABLE student CHANGE name stud_name VARCHAR(20)

SQL constraints are used to specify rules for data in a table.


New Section 1 Page 4
SQL constraints are used to specify rules for data in a table.
SQL NOT NULL Constraint
By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot
insert a new record, or update a record without adding a value to this field.

CREATE TABLE Persons ( ID int NOT NULL,


LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

New Section 1 Page 5


SQL UNIQUE Constraint
SQL UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

SQL UNIQUE Constraint on CREATE TABLE


The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is created:
SQL Server / Oracle / MS Access:

CREATE TABLE Persons (

ID int NOT NULL UNIQUE,

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Age int

);

MySQL:

CREATE TABLE Persons (

ID int NOT NULL,

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Age int,

UNIQUE (ID)

);

To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons (

ID int NOT NULL,

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Age int,

CONSTRAINT oit UNIQUE (ID,LastName)

);

SQL UNIQUE Constraint on ALTER TABLE


To create a UNIQUE constraint on the "ID" column when the table is already created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons

ADD UNIQUE (ID);

To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons

ADD CONSTRAINT oit UNIQUE (ID,LastName);

DROP a UNIQUE Constraint


New Section 1 Page 6
DROP a UNIQUE Constraint
To drop a UNIQUE constraint, use the following SQL:
MySQL:

ALTER TABLE Persons

DROP INDEX oit;

SQL Server / Oracle / MS Access:

ALTER TABLE Persons

DROP CONSTRAINT oit;

SQL PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

SQL PRIMARY KEY on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:
MySQL:

CREATE TABLE Persons (

ID int NOT NULL, CREATE TABLE Persons (

LastName varchar(255) NOT NULL, ID int primary key NOT NULL,

FirstName varchar(255), LastName varchar(255) NOT NULL,

Age int, FirstName varchar(255),

PRIMARY KEY (ID) Age int);

);

CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int,
CONSTRAINT oit UNIQUE (ID,LastName) )
insert into persons values(101,'abc','xyz',23)
insert into persons values(102,'abc','xyz',23)
ALTER TABLE Persons DROP CONSTRAINT oit
CREATE TABLE Persons1 ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255),
Age int CHECK (Age>=18) )
insert into persons1 values(123,'abc','xyz',26)
ALTER TABLE Persons1 add CONSTRAINT CHECK (Age>=1 and Age<=125)

CREATE TABLE Persons2 ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age in
t, City varchar(255), CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes' or City=
'Pune' ) )

New Section 1 Page 7


SQL DEFAULT Constraint
The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.

SQL DEFAULT on CREATE TABLE


The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is created:
My SQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons (

ID int NOT NULL,

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Age int,

City varchar(255) DEFAULT 'Sandnes'

);

CREATE TABLE Persons3 ( Personid int NOT NULL AUTO_INCREMENT, LastName varchar(255) NOT NU
LL, FirstName varchar(255), Age int, PRIMARY KEY (Personid) )
insert into persons3(LastName,FirstName,Age) values('sam','nigade',8)
SELECT * FROM `persons3`
insert into persons3(LastName,FirstName,Age) values('Ram','Shah',34)
SELECT * FROM persons3

New Section 1 Page 8


create table emp(eno int primary key,ename varchar(20),designation varchar(20),salary float,dat
e_of_joining varchar(20))
desc emp
insert into emp(eno,ename,designation,salary,date_of_joining)
values(1,'Mr.Advait','Assistant',54000,'23/03/2002')
insert into emp(eno,ename,designation,salary,date_of_joining)
values(4,'Mr.Raghav','manager',420000,'01/03/2003')
select * from emp

alter table emp add column email varchar(20)

update emp set email='[email protected]' where eno=1

SELECT * FROM `emp`

update emp set salary=salary+(salary*0.05)


SELECT * FROM `emp`

New Section 1 Page 9


Add column phone_No into Emp table with data type int.

Update Dateofjoining of employee to ‘15/06/2019’ whose name is “Mr. Roy’ and belongs to mumbai
city.

Change Dateofjoining of employee ‘olddate ’ to ' new date'.

New Section 1 Page 10


New Section 1 Page 11
create table emp(eno int primary key,ename varchar(20),designation varchar(20),salary float,date_of_joini
ng varchar(20))
desc emp
insert into emp(eno,ename,designation,salary,date_of_joining)
values(1,'Mr.Advait','Assistant',54000,'23/03/2002')
insert into emp(eno,ename,designation,salary,date_of_joining)
values(4,'Mr.Raghav','manager',420000,'01/03/2003')

New Section 1 Page 12


SELECT salary,designation FROM `emp` WHERE eno=4
SELECT eno,ename FROM `emp` WHERE salary>50000
SELECT * FROM `emp` WHERE salary<200000
SELECT * FROM `emp`
SELECT * FROM `emp` WHERE salary>56700
SELECT * FROM `emp` WHERE salary>=56700
SELECT * FROM `emp` WHERE salary<>56700

New Section 1 Page 13


SELECT * FROM `emp` WHERE salary>=100000 and designation='ceo'

SELECT * FROM `emp` WHERE salary>=100000 or designation='ceo'

The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct)
values.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2, ...

FROM table_name;

SELECT distinct city FROM Customers where CustomerID>=6 and country='UK';

New Section 1 Page 14


SELECT distinct city FROM Customers where CustomerID>=6 and country='UK';

SELECT productname,price
FROM Products
WHERE Price BETWEEN 5 AND 30;

SELECT * FROM Customers


WHERE City IN ('Paris','London');

New Section 1 Page 15


WHERE City IN ('Paris','London');

SQL LIKE Operator


The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
• The percent sign (%) represents zero, one, or multiple characters
• The underscore sign (_) represents one, single character

LIKE Operator Description

WHERE CustomerName LIKE Finds any values that start with "a"
'a%'
WHERE CustomerName LIKE Finds any values that end with "a"
'%a'
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'
WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'
WHERE CustomerName LIKE Finds any values that start with "a" and are at least 2
'a_%' characters in length
WHERE CustomerName LIKE Finds any values that start with "a" and are at least 3
'a__%' characters in length
WHERE ContactName LIKE 'a% Finds any values that start with "a" and ends with "o"
o'

NOT Example
The following SQL statement selects all fields from "Customers" where
country is NOT "Germany":
Example

New Section 1 Page 16


The following SQL statement selects all fields from "Customers" where
country is NOT "Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';

The SQL ORDER BY Keyword


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

SELECT * FROM Customers


ORDER BY city desc;

SELECT *
FROM Customers
where customerid>=60 ORDER BY customerid desc;

SELECT *
FROM Customers
where customerid>=60 and city like 's%' order by customerid ;

The SQL SELECT TOP Clause


The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of records. Returning a large
number of records can impact performance.

SELECT column_name(s) SELECT TOP number|percent column_name(s)


FROM table_name FROM table_name
WHERE condition WHERE condition;
LIMIT number;
>

SELECT *

New Section 1 Page 17


>

SELECT *
FROM Customers
LIMIT 3;

SELECT top 3 city


FROM Customers
where city like '%a' ;

The SQL MIN() and MAX() Functions


The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.

SELECT MIN(Price)
FROM Products;

MAX() Example
The following SQL statement finds the price of the most expensive product:

Example

New Section 1 Page 18


SELECT MAX(Price) AS LargestPrice

FROM Products;

The SQL COUNT(), AVG() and SUM() Functions


The COUNT() function returns the number of rows that matches a specified criterion.

COUNT() Syntax
SELECT COUNT(column_name)

FROM table_name

WHERE condition;

The AVG() function returns the average value of a numeric column.

AVG() Syntax
SELECT AVG(column_name)

FROM table_name

WHERE condition;

The SUM() function returns the total sum of a numeric column.

SUM() Syntax
SELECT SUM(column_name)

FROM table_name

WHERE condition;

SELECT COUNT(*) as no_of_records


FROM Products;

SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.

New Section 1 Page 19


Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
Alias Column Syntax
SELECT column_name AS alias_name
FROM table_name;
Alias Table Syntax
SELECT column_name(s)
FROM table_name AS alias_name;

SQL UNION Operator


The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order

UNION Syntax
SELECT column_name(s) FROM table1

UNION

SELECT column_name(s) FROM table2;

UNION ALL Syntax


The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:

SELECT column_name(s) FROM table1

UNION ALL

SELECT column_name(s) FROM table2;

SELECT City, Country FROM Customers


WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

The SQL GROUP BY Statement


The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more
columns.

GROUP BY Syntax
SELECT column_name(s)

FROM table_name

WHERE condition

GROUP BY column_name(s)

ORDER BY column_name(s);

Ex
SELECT count(CustomerID), Country
FROM Customers
GROUP BY Country
having CustomerID>=50 ;

SELECT COUNT(CustomerID), Country


FROM Customers
New Section 1 Page 20
FROM Customers
GROUP BY Country
having CustomerID>=10
ORDER BY COUNT(CustomerID) DESC;

The SQL HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.

HAVING Syntax
SELECT column_name(s)

FROM table_name

WHERE condition

GROUP BY column_name(s)

HAVING condition

ORDER BY column_name(s);

New Section 1 Page 21


Display the name of department whose location is “Pune” and “Mr. Advait” is working in it

New Section 1 Page 22


Create a RDB in 3 NF with appropriate data types and
Constraints. Emp(eno ,ename ,designation ,salary, Date_Of_Joining)
Dept(dno,dname ,loc)
The relationship between Dept & Emp is one-to-many. Constraints: - Primary Key, ename should
not be NULL, salary must be greater than 0.

create table dept(dno int primary key,dname varchar(20),loc varchar(10));

insert into dept(dno,dname,loc)values(101,'computer','pune');


insert into dept(dno,dname,loc)values(102,'computer science','mumbai');
insert into dept(dno,dname,loc)values(103,'Quqlity','mumbai');

New Section 1 Page 23


create table dept(dno int primary key,dname varchar(20),loc varchar(10));

insert into dept(dno,dname,loc)values(101,'computer','pune');


insert into dept(dno,dname,loc)values(102,'computer science','mumbai');
insert into dept(dno,dname,loc)values(103,'Quqlity','mumbai');

create table emp(eno number primary key,ename varchar(20),designation varchar(20),salary int,date_of_joining


varchar(20),dno int references dept(dno));

insert into emp(eno,ename,designation,salary,date_of_joining,dno)values(1,'Mr. Advait','Assistant',54000,'23/03/2002',101);

insert into emp(eno,ename,designation,salary,date_of_joining,dno)values(2,'Mr. Roy','ceo',50000,'15/06/2019',102);

insert into emp(eno,ename,designation,salary,date_of_joining,dno)values(3,'Mr. Abhay','manager',60000,'10/06/2013',102);

insert into emp(eno,ename,designation,salary,date_of_joining,dno)values(4,'Mr.


Raghav','manager',420000,'01/03/2003',103);

Add column phone_No into Emp table with data type int.

Delete the details of Employee whose designation is ‘Manager’.

Display the count of employees department wise.

Display the name of employee who is ‘Manager’ of “Account Department”.

Display the name of department whose location is “Pune” and “Mr. Advait” is working in it

New Section 1 Page 24


Display the name of department whose location is “Pune” and “Mr. Advait” is working in it

Display the names of employees whose salary is greater than 50000 and department is
“Quality”.

Update Dateofjoining of employee to ‘15/06/2019’ whose department is ‘computer science’ and name is
“Mr. Roy’.

Sales_order (ordNo, ordDate,Sales_order)


Client (clientNo, ClientName, addr)
The relationship between Client & Sales_order is one-to-many.
Constraints: - Primary Key, ordDate should not be NULL

1. Add column amount into sales_amt table with data type float.

2. Delete the details of the clients whose names start with ‘A’ character.

3. Delete sales order details of client whose name is “Patil” and order date is “09/08/2019”.

4)Change order date of client_No ‘CN001’ ‘18/03/2019’.

5) Delete all sales_record having order date is before ‘10 /02/2018’.

6) Update the address of client to “Pimpri” whose name is ‘Mr. Roy’

7)diplay totals orders beween 1jan2022 to 31 jan 2022

8)diplay totals sale amount beween 1jan2022 to 31 jan 2022

9)diplay total no of customers from pune location

Consider the following entities and their relationships. Create a RDB in 3 NF with appropriate data types and Constraints. [15
Marks]
Hospital (hno ,hname , city, Est_year, addr)
Doctor (dno , dname , addr, Speciality,salary)
The relationship between Hospital and Doctor is one - to – Many Constraints: - Primary Key, Est_year should be greater than
1990.

1. Delete addr column from Hospital table.

2. Display doctor name, Hospital name and specialty of doctors from “Pune City” .

3. Display the names of the hospitals which are located at “Pimpri” city.

4. Display the names of doctors who are working in “Birla” Hospital and city name is “Chinchwad”

New Section 1 Page 25


4. Display the names of doctors who are working in “Birla” Hospital and city name is “Chinchwad”

5. Display the specialty of the doctors who are working in “Ruby” hospital.

6. Give the count of doctor’s hospital wise which are located at “Pimple Gurav”.

7. Update an address of Doctor to “Pimpri” whose hospital is “Ruby clinic”

8. display doctor details whose speciality is Heart Surgen and whole belong to hospital from pune

9. Update an address of hospital to “Pimpri” whose hospital is estableshed in “2000”


10.Display Total salary of all doctors hopitalwaise

11.Display annual salary of doctor who live in Pune.

Q3. Consider the following entities and their relationships. Create a RDB in 3 NF with appropriate data types and Constraints.
Project (pno, pname, start_date, budget, status) 2
Department (dno, dname, HOD, loc) 1
The relationship between Project and Department is Many to One. Constraint: Primary key. Project Status Constraints:
C – Completed,
P - Progressive,
I – Incomplete

1. Drop loc column from department table.

2. Display the details of project whose start_date is before one month and status is “Progressive”

3. Display the names of project and department who are worked on projects whose status is ‘Completed’

4. Display total budget of each department.

5. Display incomplete project of each department.

6. Display all project working under 'Mr.Desai'.

7 .Display department wise HOD.

8.Display project details where project name start with A and whose budget is >10000 in descending order

9.Display the project detials whose having highest budget

Create a RDB in 3 NF with appropriate data types and Constraints. [15 Marks]
Customer (cust_no, cust_name, address, city)
Loan (loan_no, loan_amt)
The relationship between Customer and Loan is Many to Many Constraint:
Primary key, loan_amt should be > 0.

New Section 1 Page 26


Delete the details of customer whose loan_amt<1000.

2. List all customers whose name starts with 'D' character.

New Section 1 Page 27

You might also like