SQL Queries: 1.to Implement Various DDL, DML, DCL Commands in SQL
SQL Queries: 1.to Implement Various DDL, DML, DCL Commands in SQL
1.CREATE TABLE: Tables are defined with the CREATE TABLE command. When a table is created. Its
columns are named, data types and sizes are supplied for each column. Each table must at least have
one column. The syntax of CREATE TABLE command is:
SQL command:
( ecode integer,
ename char(20),
sex char(1),
grade char(2),
gross decimal);
Output:
emp
Syntax:
The new column will be added with NULL values for all rows currently in the table.
For instance, to add a new column tel_no of type integer in table emp
OUTPUT:
emp
3. DROP TABLE: This command lets us drop a table from the database. The SQL requires us to empty
a table before we eliminate from the database. To remove all the rows from the table, we use DELETE
command.
4. CREATE VIEW: A view is a virtual table with no data, but can be operated like any other table.
CREATE VIEW taxpayee AS
SELECT*
FROM emp
WHERE gross>8000;
This query creates a view which contains only those rows of table emp where value of gross is greater
than 8000.
5. DROP VIEW: To delete a view from the database the DROP VIEW command is used.
DROP VIEW taxpayee
Drops the view taxpayee from the database. When a view is dropped , it does not cause any change in
its base table.
DATA MANIPULATION LANGUAGE: After the database scheme has been specified and the database
has been created, the data can be manipulated using a set of procedures which are expressed by data
manipulation language (DML). Manipulation means retrieval, insertion, deletion, modification of
information.
The Insert command: The rows (tuples) are added to relations using INSERT command.
SYNTAX:
Output:
emp
INSERT command can also be used to take values from one table and place them in another using it with
a query.
OUTPUT:
emp1
2. The SELECT command: It lets us make queries on the database. A query is a command that is given
to produce certain specified information from the database.
SYNTAX:
FROM <table-name>;
QUERY:
FROM emp;
OUTPUT:
Ecode Ename
1001 Priya
1002 Prateek
1003 Hardik
1004 Sakshi
1005 Eti
1006 Priya
FROM emp;
OUTPUT:
By default, data is selected from all the rows of the table, even if the data appearing in the result is
duplicated. The DISTINCT keyword eliminates duplicate rows from the result of a select statement.
SELECT DISTINCT ename
FROM emp;
Ename
Priya
Prateek
Hardik
Sakshi
Eti
Whenever distinct is used, only one NULL value is returned in the results, no matter how many NULL
values are encountered.
3. The DELETE command: It removes the rows from a table. It removes the entire rows, not the
individual field values, so no field argument is needed or accepted.
SYNTAX:
[WHERE<predicate>];
WHERE gross>6000.00;
4.The UPDATE command: It is used to change some or all of the values in a existing row. It specifies the
row to be changed using WHERE clause, and the new data using the SET keyword. The new data can be
specified as a constant, an expression or data from other tables.
UPDATE emp
SET grade=B2
WHERE gross=4450;
OUTPUT: emp
When we create a table, we can place constraints on the values that can be entered into its fields. If this
is specified, SQL will reject any values that violate the criteria we define.
The two basis types of constraints are column constraints and table constraints. The difference between
the two is that former applies to individual columns and the latter to groups of one or more columns.
SYNTAX:
Different constraints:
These constraints ensure database integrity, thus are sometimes called database integrity constraints.
1.Unique constraint. It ensures that no two rows have the same value in the specified column(s).
2.Primary Key Constraint: It declares the column as primary key of the table. This is similar to unique
constraint except that only one column(or one group of column) can be applied in this constraint.
3.Default constraint: A default value can be specified for a column using the default clause. When user
does not specify a value for the column(having default value, the defined value is inserted in the field.
4.NOT NULL constraint: When we want a field to be not null, we specify the constraint NOT NULL
against the field. In that case, an attempt to enter a null value raises an error.
5.CHECK constraint: This constraint limits values that can be inserted into a column of a table
Now we redefine the schema of table emp by applying various constraints on its attributes.
ename char(20),
sex char(1),
The above definition of table employee specifies that ecode is the PRIMARY KEY of the table, ename and
sex fields cannot be left unspecified, if no value is specified for a grade,’E1’ wll serve as a default value
and finally gross value should be greater than 2000.
VALUES(1001, ‘Priya’,’F’,’A1’,8670.00);
VALUES(1002,’Prateek’,’M’,’A2’,7560.00);
VALUES(1003,’Hardik’,’M’,6325.00);
VALUES(1004, ‘Sakshi’,’F’,5120.00);
VALUES(1005,’Eti’,’F’,4450.00);
VALUES(1006,’Priya’,’F’,’B2’,5000.00);
employee
Since all the constraints are satisfied, no error is raised and default value is inserted where not specified.
To explore SELECT clause using WHERE, ORDER BY, GROUP BY, HAVING clauses and using BETWEEN and
LIKE operators.
The WHERE clause in SELECT statement specifies the criteria for selection of rows to be returned.
SYNTAX:
SELECT <column-name>…..
FROM <table-name>
WHERE <condition>;
To display the ename and ecode for the employees whose gross is greater than 4000.
FROM emp
WHERE gross>5000;
1001 Priya
1002 Prateek
1003 Hardik
1004 Sakshi
The BETWEEN operator defines a range of values that the column values must fall in to make the
condition true.
To display the ename, ecode and grade of all employee whose gross is in between 5000 to 7000(both
inclusive).
FROM emp
SQL includes a string matching operator, LIKE, for comparisons on character strings using patterns.
Patterns are described using two special wildcard characters:
To display ename and grade of those employees where ename starts with Har or contains the string
aksh or is 3 letters long.
FROM emp
Ename Grade
Hardik B1
Sakshi B2
Eti C1
Order By Clause: Whenever a SELECT query is executed, the resulting rows emerge in a predefined
order. We can sort the results of a query in a specific order using ORDER BY clause. The ORDER BY clause
allows sorting of query results by one or more columns. The sorting can be done either in ascending
order or descending order, the default order is ascending. The data in the table is not sorted ; only the
results that appear on the screen are sorted.
SYNTAX:
SELECT <column-name>…
FROM<table-name>
[WHERE<predicate>]
[ORDER BY <column-name>];
To display the grades of all the employees in descending order. If more than one employee has same
grade,display them in ascending order.
SELECT *
FROM emp
GROUP BY CLAUSE: It is used in SELECT statements to divide the table into groups. Grouping can be
done by a column name , or with aggregate functions an which case the aggregate produces a value for
each group.
To calculate the no. of employees in each grade and average gross for each grade of employees.
FROM emp
GROUP BY grade;
grade Count(*) Sum(gross)
A1 1 8670
A2 1 7560
B1 1 6325
B2 2 10120
C1 1 4450
Placing conditions on groups- HAVING clause: It places conditions on groups in contrast to WHERE
clause that places conditions on individual rows. While where conditions cannot include aggregate
functions, HAVING conditions can do so.
To calculate the average gross and total gross for employees belonging to ‘B2’ grade.
FROM emp
GROUP BY grade
HAVING grade=’B2’;
Avg(gross) Sum(gross)
560 10120
3.To implement different inbuilt functions on table emp
i) Aggregate Functions: The summary values are calculated from data in a particular column using
aggregate functions. The result of aggregate functions is a single value.
min-to find minimum value count- to count non null values in a column
sum- to find total value variance-to compute the variance of values in a coloumn
FROM emp;
max (gross)
8670
SELECT count(*)
FROM emp;
count(*)
6
3.INITCAP(col/exp)- converts alpha character values to upper case for first letter of each word.
iii).Character Manipulation Function:
1.CONCAT(col1/exp1, col2/exp2)- Concatenates the first character value to the second character value.
4. INSTR(col/exp, ‘string’,[m],[n])- returns the numeric position of a named string (optionally we can
provide a position m to start searching an occurrence n of the string). By default m and n are equal to 1.
5.LPAD(col/exp, n, ‘character’)- pads the character value right justified to a total of n character postion.
6.RPAD(col/exp,n,’character’)- pads the character value left justified to a total of n character position.
7. TRM( heading/trailing/both, trim char from trim source)- enables us to heading or trailing or both
from a character string (if trim char and trim source is a characterthen we must enclose it in single
quotes).This is a feature available from oracle 8i and its successors.
8.Replace(text, searchstring, replacementstring)-It searches a text expression for a character string and
if found replaces it with a specified replacement string.
ex. ROUND(193.329)=193.33
ex-TRUNC(193.329,1)=193.32
ex. MOD(400,70)=50
v) Date conversion functions:
1. months_between(‘date1’, ‘date2’)- here date1 is greater than date2. it return the no. of months
between these two dates.
2.Add_months(date, n)- adds n months to the no of month specified in date and returns the modified
date.
3.Next_day(date, ‘day’)- returns the next date on which specified day comes i.e. if day is specified as
Monday then it would return the date of next Monday from the specified date.
4. Last_day(date)
5.Round(date, int)
Now consider the following table “emprecord” for the queries to implement all the above inbuilt
functions.
emprecord
1.Create a query to display first name of all employee with first letter as capital, last name with all the
letters capital and concatenate first name and lastname as ename, length of first name as len. format
the salary to be10 characters long left padded with dollar sign.
FROM emprecord;
ename len salary
Priya KAPOOR 11 $$$$$45000
Prateek SAXENA 13 $$$$$50000
Sakshi MALHOTRA 14 $$$$$47000
Hardik DSOUZA 12 $$$$$43000
2. For each employee display the employees’ last name and calculate the no of months between
today(15-Sep-09) and the date on which emp was hired. Order your result by no. of months and round
the no. of months upto the closest whole no.
FROM emprecord
ORDER BY emonths;
lname emonths
malhotra 9
dsouza 12
kapoor 12
saxena 20
3. Display each employees’ first name, hire date and salary review date( which is the first MONDAY
after six months of service). label the column as review.
FROM emprecord;
account
branch
customer
depositor
customer_name account_no
hayes A-102
Johnson A-101
Johnson A-201
jones A-217
Lindsay A-222
smith A215
turner A-305
loan
borrower
customer_name loan_no
adams L-16
curry L-93
hayes L-15
Jackson L-14
jones L-17
smith L-11
smith L-23
Williams L-17
Test for set membership:
The in connective tests for set membership, where the set is a collection of values produced by select
clause. The not in connective tests for the absence of set membership.
Find all the customers who have both a loan and an account at the bank.
from borrower
from depositor)
customer name
hayes
jones
smith
find all the customers who have both an account and a loan at the perryridge branch.
branch_name=”perryridge” and
(branch_name, customer_name) in
where depositor.account_no=account.account_no)
customer name
hayes
find all the customers who do have a loan at the bank, but do not have an account at the bank.
from borrower
from depositor)
customer name
adams
curry
Jackson
Williams
2. Set comparisons
find the names of all the branches that have assets greater than those of at least one branch located
in Brooklyn.
from branch
from branch
where branch_city=”brooklyn”);
branch_name
mianus
north town
perryridge
pownal
redwood
roundhill
find the names of all the branches that have an asset value greater than that of each branch in
brooklyn.
select branch_name
from branch
from branch
where branch_city=”brooklyn”);
branch_name
roundhill
5.To implement various Join operations.
SQL provides not only the basic cartesian-product mechanism for joining tuples of relations, but also
provides various other mechanisms for joining relations including condition joins and natural joins, as
well as various forms of outer joins. These additional operations are typically used as subquery
expressions in the FROM clause.
loan
borrower
customer_name loan_no
jones L-170
smith L-230
hayes L-155
1.Inner join: The inner join is a binary operation that allows us to combine certain sections
and a Cartesian_product into one operation. It retains duplicate attributes.
i) left outer join: it takes all the tuples in the left relation that did not match with any tuple in the
right relation, pads the tuples with null values for all other attributes from right relation, and adds them
to the result of the inner join.
ii) Right outer join: it is symmetric with outer join: It pads tuples from the right relation that did not
match any from the left relation with nulls and adds them to the result of the inner join.
iii) Full outer join: It does both those operation, padding tuples with null from the left relation that did
not match any from the right relation, as well as tuples from the right relation that did not match any
from the left relation, and adding them to the result of inner join.