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

6.SQL Queries Clause

The document provides an overview of SQL queries, focusing on various clauses such as WHERE, AND, OR, LIKE, BETWEEN, and ORDER BY. It explains the use of wildcard characters, group functions, and aggregate functions, along with examples for each. Additionally, it covers substitution variables and their usage in SQL statements.

Uploaded by

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

6.SQL Queries Clause

The document provides an overview of SQL queries, focusing on various clauses such as WHERE, AND, OR, LIKE, BETWEEN, and ORDER BY. It explains the use of wildcard characters, group functions, and aggregate functions, along with examples for each. Additionally, it covers substitution variables and their usage in SQL statements.

Uploaded by

dharani thaneeru
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 40

SQL QUERIES-4

CLAUSES
1.WHERE CLAUSE
• The WHERE clause is used to extract only those
records that fulfill a specified criterion.
• SELECT column_name,column_name
FROM table_name WHERE column_name operator
value;
• Select * from student where id=3;
• Select namr from student where id=3;
• WHERE clause uses some conditional selection.
• insert into student where = equal
> greater than
(cgpa=5 and cgpa<=8); < less than

and so on. >= greater than or


equal
<= less than or
equal
!= not equal to
SQL AND
• The SQL AND condition is used in SQL query to create
two or more conditions to be met.
• It is used in SQL SELECT, INSERT, UPDATE and DELETE
statements.Let's see the syntax for SQL AND:
SELECT columns FROM tables WHERE condition 1 AND condition 2;

• The SQL AND condition requires that both conditions


should be met.
• The SQL AND condition also can be used to join
multiple tables in a SQL statement.
• Rest of AND CLAUSE will be discussed later on
3.SQL OR
• The SQL OR condition is used in a SQL query to
create a SQL statement where records are returned
when any one of the condition met. It can be used
in a SELECT statement, INSERT statement, UPDATE
statement or DELETE statement.Syntax
• SELECT columns FROM tables WHERE condition 1
OR condition 2;
• SELECT * FROM suppliers WHERE city = 'New York
' OR available_products >= 250;
• SELECT * FROM suppliers WHERE city = 'New York' OR availa
ble_products >= 250;

• INSERT INTO suppliers(supplier_id, supplier_name) SELE


CT account_no, name FROM customers WHERE city = 'Ne
w Delhi' OR city = 'Ghaziabad';

• UPDATE suppliers SET supplier_name = 'HP' WHERE sup


plier_name = 'IBM' OR available_product >36;

• DELETE FROM suppliers WHERE supplier_name = 'IBM'


OR employee <=100;
4.LIKE Clause

• Like clause is used as condition in SQL


query. Like clause compares data with an
expression using wildcard operators. It is used to
find similar data from the table.
• SELECT column_name(s) FROM table_name
WHERE column_name LIKE pattern;
5.WILDCARD CHARACTERS
• A wildcard character can be used to substitute for any other
character(s) in a string and are used with the SQL LIKE
operator.
• SQL wildcards are used to search for data within a table.
• With SQL, the wildcards are:
Wildcard Description

% A substitute for zero or more characters

_ A substitute for a single character

[charlist] Sets and ranges of characters to match

[^charlist] Matches only a character NOT specified within


or the brackets
[!charlist]
DEMO DATABASE
CustomerID CustomerN ContactNa Address City PostalCode Country
ame me
1 Alfreds Maria Obere Str. Berlin 12209 Germany
Futterkiste Anders 57

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedad Constitució
os y n 2222
helados
3 Antonio Antonio Mataderos México D.F. 05023 Mexico
Moreno Moreno 2312
Taquería
4 Around the Thomas 120 London WA1 1DP UK
Horn Hardy Hanover Sq.

5 Berglunds Christina Berguvsväg Luleå S-958 22 Sweden


snabbköp Berglund en 8
• Using the SQL % Wildcard
• The following SQL statement selects all customers
with a City starting with "ber":Example
• SELECT * FROM Customer WHERE City LIKE 'ber%';
• The following SQL statement selects all customers
with a City containing the pattern "es":Example
• SELECT * FROM Customers WHERE City LIKE '%es%';
Using the SQL _ Wildcard
• The following SQL statement selects all customers
with a City starting with any character, followed by
"erlin":Example
• SELECT * FROM Customers WHERE City LIKE '_erlin';
• The following SQL statement selects all customers
with a City starting with "L", followed by any
character, followed by "n", followed by any
character, followed by "on":Example
• SELECT * FROM Customers WHERE City LIKE 'L_n_on';
Using the SQL [charlist] Wildcard
• The following SQL statement selects all customers with a City
starting with "b", "s", or "p":Example
• SELECT * FROM Customers WHERE City LIKE '[bsp]%';
• The following SQL statement selects all customers with a City
starting with "a", "b", or "c":Example
• SELECT * FROM Customers WHERE City LIKE '[a-c]%';
• The following SQL statement selects all customers with a City
NOT starting with "b", "s", or "p":Example
• SELECT * FROM Customers WHERE City LIKE '[!bsp]%';
• Or
• SELECT * FROM CustomersWHERE City NOT LIKE '[bsp]%';
6.BETWEEN Operator
• The BETWEEN operator selects values within a
range. The values can be numbers, text, or dates.
• SQL BETWEEN Syntax
• SELECT column_name(s) FROM table_name
WHERE column_name BETWEEN value1 AND value2;
eg:Select * from student where id between 1101 and 1103;
• To display the products outside the range of the previous
example, use NOT BETWEEN: Example
• SELECT * FROM student WHERE id NOT BETWEEN 1101 AND
1103;
• BETWEEN Operator with IN Example
• The following SQL statement selects all products with a price
BETWEEN 10 and 20, but products with a CategoryID of 1,2,
or 3 should not be displayed:
SELECT * FROM Products WHERE (Price BETWEEN 10
AND 20)AND NOT CategoryID IN (1,2,3);
• BETWEEN Operator with Text Value Example
• The following SQL statement selects all products with a ProductName
beginning with any of the letter BETWEEN 'C' and 'M':

SELECT * FROM Products WHERE ProductName


BETWEEN 'C' AND 'M';
• In some databases, BETWEEN selects fields that are
between and excluding the test values.
• In other databases, BETWEEN selects fields that are
between and including the test values.

• in other databases, BETWEEN selects fields


between the test values, including the first test
value and excluding the last test value(12c and
11g).
#SQL ORDER BY Clause
• The SQL ORDER BY clause is used for sorting data in
ascending and descending order based on one or
more columns.
• Some databases sort query results in ascending
order by default.
• To sort data in descending order DESC keyword is
used withOrder by clause.
• SELECT expressions FROM tables WHERE conditio
ns ORDER BY expression [ASC | DESC];
• select * from student order by name desc;
• This statement is used to sort data in ascending
order. If you miss the ASC attribute, SQL ORDER BY
query takes ascending order by default.
• SELECT supplier_city FROM suppliers WHERE sup
plier_name = 'IBM' ORDER BY supplier_city;
• This statement is used to sort data in descending
order. You should use the DESC attribute in your
ORDER BY clause as follows.
• SELECT supplier_city FROM suppliers WHERE sup
plier_name = 'IBM' ORDER BY supplier_city DESC;

• If you want the resulting record to be ordered
randomly, you should use the following codes
• SELECT * FROM table ORDER BY
DBMS_RANDOM.RANDOM
• Eg:
• Select * from (Select * from student order by
dbms_random.random);
• ORDER BY ASC places NULL values at the end of the query results. ORDER
BY DESC places null values at the start of the query results.
• The default placement of NULLs with ORDER BY can be changed with the
addition of NULLS FIRST/NULLS LAST to the ORDER BY clause.
• Instead of column names in the SELECT list, column positions oraliases can be
specified to order rows. The position value must be an integer.
• Instead of column names in the SELECT list,
column positions oraliases can be specified to order rows. The
position value must be an integer.
• Eg: select * from student order by 3;
• (it will order according to the third column)
• SORTING ON MULTIPLE COLUMNS
• Let's take an example of customer table which has many
columns, the following SQL statement selects all customers
from the table named "customer", stored by the "country" and
"Customer-Name" columns:
• SELECT * FROM customers ORDER BY country, Custome
r-Name;
• GROUP BY
What Are Group Functions?
• Group functions operate on sets of rows to give one
result per group.
EMPLOYEES

Maximum salary in
EMPLOYEES table


Types of Group Functions
– AVG
– COUNT
– MAX
– MIN
– STDDEV
– SUM
– VARIANCE Group
functions
• SQL GROUP BY Syntax
• SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator
value GROUP BY column_name;
SQL AGGREGATE FUNCTIONS

• SQL aggregate functions return a single value, calculated


from values in a column.Useful aggregate functions:
• AVG() - Returns the average value
• COUNT() - Returns the number of rows
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum
Demo Database
• Consider following Emp table

eid name age salary


401 Anu 22 9000
402 Shane 29 8000
403 Rohan 34 6000
404 Scott 44 10000
405 Tiger 35 8000
• 1) AVG()
• Average returns average value after calculating
from values in a numeric column.
• Its general Syntax is,
• SELECT AVG(column_name) from table_name;
• SQL query to find average of salary will be,
• SELECT avg(salary) from Emp; Result of the above
query will be,
• avg(salary)8200
• 2) COUNT()
• Count returns the number of rows present in the
table either based on some condition or without
condition.Its general Syntax is,
• SELECT COUNT(column_name) from table-name;
• SELECT COUNT(name) from Emp where salary = 8000;
Result of the above query will be, count(name)2

• SELECT COUNT(distinct salary) from emp; Result of


the above query will be,
• count(distinct salary)4
• 3) MAX()
• MAX function returns maximum value from
selected column of the table.
• Syntax of MAX function is,
• SELECT MAX(column_name) from table-name;
• SQL query to find Maximum salary is,
• SELECT MAX(salary) from emp;
4.MIN()
• MIN function returns minimum value from a
selected column of the table.
• Syntax for MIN function is,
• SELECT MIN(column_name) from table-name;
• QL query to find minimum salary is,
• SELECT MIN(salary) from emp; Result will be,
• MIN(salary)6000
5.SUM()
• SUM function returns total sum of a selected
columns numeric values.
• Syntax for SUM is,
• SELECT SUM(column_name) from table-name;
• SQL query to find sum of salaries will be,
• SELECT SUM(salary) from emp;
l

6. UPPER()
• UCASE function is used to convert value of string
column to Uppercase character.
• Syntax of UCASE,
• SELECT UPPER(column_name) from table-name;
• SQL query for using UPPER is,
• SELECT UPPER(name) from emp;
7.LOWER()
• LCASE function is used to convert value of string
column to Lowecase character.
• Syntax for LCASE is,
• SELECT LCASE(column_name) from table-name;
• SQL query for converting string value to Lower case
is,
• SELECT LCASE(name) from emp;
8. SUBSTR()
• MID function is used to extract substrings from
column values of string type in a table.
• Syntax for MID function is,
• SELECT substr(column_name, start, length) from
table-name;
• SQL query will be,
• select substr(name,2,2) from emp;
9.ROUND()
• ROUND function is used to round a numeric field to
number of nearest integer. It is used on Decimal
point values. Syntax of Round function is,
• SELECT ROUND(column_name, decimals) from
table-name;
• SQL query is,
• SELECT ROUND(salary) from emp;
Group By Clause
• Group by clause is used to group the results of a SELECT
query based on one or more columns. It is also used with SQL
functions to group the result from one or more tables.
• Syntax for using Group by in a statement.
• SELECT column_name, function(column_name) FROM
table_name WHERE condition GROUP BY column_name;
• Here we want to find name and age of employees grouped by
their salaries
• SQL query for the above requirement will be,
• SELECT name, age ,max(salary)from Emp group by
name ,age;
HAVING CLAUSE
SUBSTITUTION VARIABLES
• 1.used to temporarily store values with & and &&.
• 2.used with where ,order by ,select statements.
• we can use predefined variables by using define
command. define creates and assigns a value to a
variable.
• when sql developer detects that sql statement contains
an ampersand,you are prompted to enter a value for
the substitution variable that is named in sql
statement.
• after you enter a value and click ok,results are
displayed.
• after you enter a value and click ok,results are
displayed.e.g.
• 1. select * from emp where eid=&employeenum;
• enter here 401 or 402 or 403 as employeenum
• 2.select salary+12 from emp where eid='&enumb';
• 3.select eid , lastname, jobid, & columnname from
emp where &condition order by & ordercolumn
• in 3rd point,columnname can be salary,condition can
be salary>1500, ordercolumn can be lastn:
• Eg:select eid,name, &age from emp where
salary>5000 order by &name;
• ********Using && substitution variable*******
• use && if u want to reuse the variable value
without prompting use each time.
• select eid,lastname,jobid,&&columnname from
emp0 order by &columnname;
• enter salary as columnname
• no need to enter it again,every time you run the
above command same column name will be picked.
DEFINE AND VERIFY
• 1. Define-This command is used to create and assign a value to
a variable.
• 2. Undefine-To remove a variable.
• define employeenum=401;
• select * from emp where eid=&employeenum;
• insert into emp values(&eid,&name,&age,&salary);

• undefine employeenum;
• here defined variable value is automatically substituted in
select statement.
• employeenum variable is present in session until the user
undefines it or exits the sql developer session.
• Verify-to confirm the changes in sql statement
• It is used to toggle the display of substitution
variable
• set verify on
• select eid,lastname,salary,jobid from emp0 where
eid=&employeenum;
• Already present in 12c

You might also like