0% found this document useful (0 votes)
15 views15 pages

SQL SELECT Statement Basics Guide

This document provides an overview of SQL SELECT statements, including how to select all columns, use DISTINCT, and apply the WHERE clause for filtering records. It also covers operators in SQL, including comparison, arithmetic, and logical operators, as well as the DELETE statement for removing records from a table. Additionally, it includes practical lab exercises for creating and manipulating tables in SQL.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views15 pages

SQL SELECT Statement Basics Guide

This document provides an overview of SQL SELECT statements, including how to select all columns, use DISTINCT, and apply the WHERE clause for filtering records. It also covers operators in SQL, including comparison, arithmetic, and logical operators, as well as the DELETE statement for removing records from a table. Additionally, it includes practical lab exercises for creating and manipulating tables in SQL.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lab 2:

The SQL SELECT Statement

SELECT column1, column2, ...


FROM table_name;

1. Select ALL columns:

If you want to return all columns, without specifying every column name, you can use the
SELECT * syntax:

Example

Return all the columns from the Customers table:

SELECT * FROM Customers;

2. The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different)


values.

ExampleGet your own SQL Server

Select all the different countries from the "Customers" table:

SELECT DISTINCT Country FROM Customers;

3. The SQL WHERE Clause


The WHERE clause is used to filter records.
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Example

Select all customers from Mexico:

SELECT * FROM Customers


WHERE Country='Mexico';

Text Fields vs. Numeric Fields


SQL requires single quotes around text values (most database systems will also allow double
quotes).

However, numeric fields should not be enclosed in quotes:

Example
SELECT * FROM Customers
WHERE CustomerID=1;

Operators in The WHERE Clause

Operators
An operator manipulates individual data items and returns a result. The data items are called
operands or arguments. Operators are represented by special characters or by keywords. For
example, the multiplication operator is represented by an asterisk (*) and the operator that tests
for nulls is represented by the keywords IS NULL. Tables in this section list SQL operators.

Unary and Binary Operators

There are two general classes of operators:

unary A unary operator operates on only one operand. A unary operator typically appears with
its operand in this format:
operator operand
binary A binary operator operates on two operands. A binary operator appears with its
operands in this format:
operand1 operator operand2

Other operators with special formats accept more than two operands. If an operator is given a
null operand, the result is always null. The only operator that does not follow this rule is
concatenation (||).

Precedence

Precedence is the order in which Oracle evaluates different operators in the same expression.
When evaluating an expression containing multiple operators, Oracle evaluates operators with
higher precedence before evaluating those with lower precedence. Oracle evaluates operators
with equal precedence from left to right within an expression.

+, - identity, negation
*, / multiplication, division
+, -, || addition, subtraction, concatenation
=, !=, <, >, <=, >=, IS NULL, LIKE, BETWEEN, IN comparison
NOT exponentiation, logical negation
AND conjunction
OR disjunction

You can use other operators than the = operator to filter the search.

The following operators can be used in the WHERE clause:

Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Not equal. Note: In some versions of SQL this operator may be
<>
written as !=
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values for a column

Example

Select all customers with a CustomerID greater than 80:

SELECT * FROM Customers


WHERE CustomerID > 80;

Arithmetic Operators

You can use an arithmetic operator in an expression to negate, add, subtract, multiply, and divide
numeric values. The result of the operation is also a numeric value. Some of these operators are
also used in date arithmetic. Table 3-2 lists arithmetic operators.

Table 3-2 Arithmetic Operators


Operator Purpose Example

+- Denotes a positive or negative expression. SELECT * FROM orders


WHERE qtysold = -1;
These are unary operators.
SELECT * FROM emp
WHERE -sal < 0;

*/ Multiplies, divides. These are binary operators. UPDATE emp


SET sal = sal+sal * 1.1;
+- Adds, subtracts. These are binary operators. SELECT sal + comm FROM emp
WHERE SYSDATE - hiredate
> 365;

Concatenation Operator
Operator Purpose Example
|| Concatenates character strings. SELECT 'Name is ' || ename
FROM emp;

Example

This example creates a table with both CHAR and VARCHAR2 columns, inserts values both
with and without trailing blanks, and then selects these values, concatenating them. Note that for
both CHAR and VARCHAR2 columns, the trailing blanks are preserved.

CREATE TABLE tab1 (col1 VARCHAR2(6), col2 CHAR(6),


col3 VARCHAR2(6), col4 CHAR(6) );

Table created.

INSERT INTO tab1 (col1, col2, col3, col4)


VALUES ('abc', 'def ', 'ghi ', 'jkl');

1 row created.

SELECT col1||col2||col3||col4 "Concatenation"


FROM tab1;

Concatenation
------------------------
abcdef ghi jkl

Comparison Operators

Comparison operators compare one expression with another. The result of such a comparison can
be TRUE, FALSE, or UNKNOWN. For information on conditions, see "Conditions". Table 3-4
lists comparison operators.

Table 3-4 Comparison Operators


Operator Purpose Example

= Equality test. SELECT *


FROM emp
WHERE sal = 1500;

!= Inequality test. Some forms of the SELECT *


^= FROM emp
inequality operator may be
<> WHERE sal != 1500;
¬= unavailable on some platforms.

> "Greater than" and "less than" tests. SELECT * FROM emp
WHERE sal > 1500;
< SELECT * FROM emp
WHERE sal < 1500;

>= "Greater than or equal to" and "less SELECT * FROM emp
WHERE sal >= 1500;
than or equal to" tests.
<= SELECT * FROM emp
WHERE sal <= 1500;

IN "Equal to any member of" test. SELECT * FROM emp


WHERE job IN
Equivalent to "= ANY".
('CLERK','ANALYST');

NOT IN Equivalent to "!=ALL". Evaluates SELECT * FROM emp


WHERE sal NOT IN
to FALSE if any member of the set
(SELECT sal FROM emp
is NULL. WHERE deptno = 30);
SELECT * FROM emp
WHERE job NOT IN
('CLERK', ANALYST');

ANY Compares a value to each value in SELECT * FROM emp


SOME WHERE sal = ANY(10,20,30)
a list or returned by a query. Must
be preceded by =, !=, >, <, <=, >=.

Evaluates to FALSE if the query


returns no rows.
ALL Compares a value to every value in SELECT * FROM emp
WHERE sal >=
a list or returned by a query. Must
ALL ( 1400, 3000);
be preceded by =, !=, >, <, <=, >=.

Evaluates to TRUE if the query


returns no rows.
[NOT] [Not] greater than or equal to x and SELECT * FROM emp
BETWEEN WHERE sal
less than or equal to y.
x AND y BETWEEN 2000 AND 3000;

EXISTS TRUE if a subquery returns at least SELECT ename, deptno


FROM dept
one row.
WHERE EXISTS
(SELECT * FROM emp
WHERE [Link]
= [Link]);

x [NOT] TRUE if x does [not] match the See "LIKE Operator".


LIKE y
pattern y. Within y, the character
[ESCAPE "%" matches any string of zero or SELECT * FROM tab1
WHERE col1 LIKE
'z'] more characters except null. The
'A_C/%E%' ESCAPE '/';
character "_" matches any single
character. Any character, excepting
percent (%) and underbar (_) may
follow ESCAPE; a wildcard
character is treated as a literal if
preceded by the character
designated as the escape character.
IS Tests for nulls. This is the only SELECT ename, deptno
[NOT] FROM emp
operator that you should use to test
NULL WHERE comm IS NULL;
for nulls. See "Nulls".

NOT IN Operator

If any item in the list following a NOT IN operation is null, all rows evaluate to UNKNOWN
(and no rows are returned). For example, the following statement returns the string 'TRUE' for
each row:

SELECT 'TRUE'
FROM emp
WHERE deptno NOT IN (5,15);

However, the following statement returns no rows:

SELECT 'TRUE'
FROM emp
WHERE deptno NOT IN (5,15,null);

The above example returns no rows because the WHERE clause condition evaluates to:

deptno != 5 AND deptno != 15 AND deptno != null

LIKE Operator

The LIKE operator is used in character string comparisons with pattern matching. The syntax for
a condition using the LIKE operator is shown in this diagram:
While the equal (=) operator exactly matches one character value to another, the LIKE operator
matches a portion of one character value to another by searching the first value for the pattern
specified by the second. Note that blank padding is not used for LIKE comparisons.

With the LIKE operator, you can compare a value to a pattern rather than to a constant. The
pattern can only appear after the LIKE keyword. For example, you can issue the following query
to find the salaries of all employees with names beginning with 'SM':

Patterns usually use special characters that Oracle matches with different characters in the value:

 An underscore (_) in the pattern matches exactly one character (as opposed to one byte in
a multibyte character set) in the value.
 A percent sign (%) in the pattern can match zero or more characters (as opposed to bytes
in a multibyte character set) in the value. Note that the pattern '%' cannot match a null.

SELECT sal
FROM emp
WHERE ename LIKE 'SM%';

 The following query uses the = operator, rather than the LIKE operator, to find the
salaries of all employees with the name 'SM%':

SELECT sal
FROM emp
WHERE ename = 'SM%';

 The following query finds the salaries of all employees with the name 'SM%'. Oracle
interprets 'SM%' as a text literal, rather than as a pattern, because it precedes the LIKE
operator:

SELECT sal
FROM emp
WHERE 'SM%' LIKE ename;

The SQL DELETE Statement


The DELETE statement is used to delete existing records in a table.

DELETE Syntax

DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement.
The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records
in the table will be deleted!
SQL DELETE Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers"
table:

ExampleGet your own SQL Server


DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

Delete All Records


It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:

DELETE FROM table_name;

Example
DELETE FROM Customers;

Delete a Table
To delete the table completely, use the DROP TABLE statement:

Example

Remove the Customers table:

DROP TABLE Customers;

Lab Experiments for Today:


CREATION OF TABLES
1) Create a table called Employee with the following structure.
Name Type
Empno Number
Ename Varchar2(10)
Job Varchar2(10)
Mgr Number
Sal Number
a. Add a column commission with domain to the Employee table.
b. Insert any five records into the table.
c. Update the column details of job
d. Rename the column of Employ table using alter command.
e. Delete the employee whose Emp no is 105.

2) Create department table with the followingstructure.


Name Type
Deptno Number
Deptname Varchar2(10)
Location Varchar2(10)

a. Add column designation to the department table.


b. Insert values into the table.
c. List the records of dept table based on deptname.
d. Update the record where deptno is 9.
e. Delete any column data from the table.

SOLUTION:
SQL> create table employee(empno number,
ename varchar2(10),
job varchar2(10),
mgr number,
sal number);

Table created.

SQL> desc employee;


Name Null? Type
--------------------------- -------- ----------------------------
EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR NUMBER
SAL NUMBER

a. Add a column commission with domain to the Employee table.

SQL> alter table employee add(commission number);


Table altered.
SQL> desc employee;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR NUMBER
SAL NUMBER
COMMISSION NUMBER

b. Insert any five records into thetable.


SQL> insert into employee
values(&empno,'&ename','&job',&mgr,&sal,'&commission');
Enter value for empno: 101
Enter value for ename: abhi
Enter value for job: manager
Enter value for mgr: 1234
Enter value for sal: 10000 Enter value for commission:70

old 1: insert into employee


values(&empno,'&ename','&job',&mgr,&sal,'&commission') new 1: insert into
employee values(101,'abhi','manager',1234,10000,'70')
1 row created.
SQL> /
Enter value for empno: 102
Enter value for ename: rohith
Enter value for job: analyst
Enter value for mgr: 2345
Enter value for sal: 9000
Enter value for commission: 65

old 1: insert into employee


values(&empno,'&ename','&job',&mgr,&sal,'&commission') new 1: insert into
employee values(102,'rohith','analyst',2345,9000,'65')
1 row created.
SQL> /
Enter value for empno: 103
Enter value for ename: david
Enter value for job: analyst
Enter value for mgr: 3456
Enter value for sal: 9000
Enter value for commission: 65
old 1: insert into employee
values(&empno,'&ename','&job',&mgr,&sal,'&commission') new 1: insert into
employee values(103,'david','analyst',3456,9000,'65')
1 row created.
SQL> /
Enter value for empno: 104
Enter value for ename: Rahul
Enter value for job: clerk
Enter value for mgr: 4567
Enter value for sal: 7000
Enter value for commission: 55

old 1: insert into employee


values(&empno,'&ename','&job',&mgr,&sal,'&commission') new 1: insert into
employee values(104,'rahul','clerk',4567,7000,'55')
1 row created.
SQL> /
Enter value for empno: 105
Enter value for ename: pramod
Enter value for job: salesman
Enter value for mgr: 5678
Enter value for sal:5000
Enter value for commission: 50
old 1: insert into employee
values(&empno,'&ename','&job',&mgr,&sal,'&commission') new 1: insert into
employee values(105,'pramod','salesman',5678,5000,'50')
1 row created.
SQL> select * from employee;

c) Update the column details of job

SQL> update employee set job='trainee' where empno=103;


1 row updated.

SQL> select * from employee;

d. Rename the column of Employ table using alter command.

SQL> alter table employee rename column mgr to manager_no;

Table altered.

SQL> desc employee;


e. Delete the employee whose Empno is105.

SQL> delete employee where empno=105;


1 row deleted.

2) Create department table with the followingstructure

SOLUTION:

SQL> create table department


(deptno number,
Deptname varchar2(10),
location varchar2(10));

Table created.

SQL> desc department;


Name Null? Type
----------------------------------------- -------- ---------------------------- DEPTNO
NUMBER
DEPTNAME VARCHAR2(10)
LOCATION VARCHAR2(10)

a. Add column designation to the departmenttable.

SQL> alter table department add(designation varchar2(10));


Table altered.

SQL> desc department;


Name Null? Type
----------------------------------------- -------- ---------------------------- DEPTNO NUMBER
DEPTNAME VARCHAR2(10)
LOCATION VARCHAR2(10)
DESIGNATION VARCHAR2(10)

b. Insert values into thetable.

SQL> insert into department


values(&deptno,'&deptname','&location','&designation');
Enter value for deptno: 9
Enter value for deptname: accounting
Enter value for location: Hyderabad
Enter value for designation: manager
old 1: insert into department
values(&deptno,'&deptname','&location','&designation') new 1: insert into
department values(9,'accounting','hyderabad','manager')
1 row created.

SQL> /
Enter value for deptno: 10
Enter value for deptname: research
Enter value for location: chennai
Enter value for designation: professor
old 1: insert into department
values(&deptno,'&deptname','&location','&designation') new 1: insert into
department values(10,'research','chennai','professor')
1 row created.

SQL> /
Enter value for deptno: 11
Enter value for deptname:sales
Enter value for location: banglore
Enter value for designation: salesman
old 1: insert into department
values(&deptno,'&deptname','&location','&designation') new 1: insert into
department values(11,'sales','banglore','salesman')
1 row created.

SQL> /
Enter value for deptno: 12
Enter value for deptname: operations
Enter value for location: mumbai Enter value for designation: operator
old 1: insert into department
values(&deptno,'&deptname','&location','&designation') new
1: insert into department values(12,'operations','mumbai','operator')
1 row created.

SQL> insert into department


values(&deptno,'&deptname','&location','&designation'); Enter value for deptno: 9
Enter value for deptname: accounting Enter value for location: chennai Enter value
for designation: manager
old 1: insert into department
values(&deptno,'&deptname','&location','&designation') new 1: insert into
department values(9,'accounting','chennai','manager')
1 row created.

SQL> select * from department ;


c. Update the record where deptno is9.

SQL> update department set designation='accountant' where deptno=9;

2 rows updated.

SQL> select * from department;

d. Delete any column data from the table.


SQL> alter table department drop (designation);
Table altered.

SQL> select * from department;

DEPTNO DEPTNAMELOCATION
---------- --------------- ----------
9 accounting hyderabad
10 research chennai
11 sales banglore
12 operations mumbai
9 accounting Chennai

You might also like