SlideShare a Scribd company logo
1 of 51
BEN FINKEL
CBT NUGGET ON
USING THE ‘ORDER BY
CLAUSE’
A SUMMARY BY SAMUEL UKWESA
When inserting , inputting or appending data into a database, it is usually done in an uninteresting manner. It may be
done in a manner that it came in source files or any other way through which it came into your system. This also
depend on the various ways through which people key in those data.
There are different ways through which data is stored. Consequently, when you select and query the data on the
database then the such data is not especially useful. We can use the ‘order by clause’ inside of DMS to rearrange the
order of the output from the data that we see from a select statement. Consider the table below, it is an employees
table that I fill out with ten different role and a bunch of other data in it. Well I can use the ‘‘order by clause’’ to re-
order those results when I order them from the table for example, if I run this command.
Mysql> select * from employees order by Lname + a colume name.
This will display the results below in an alphabetical order based on the column name because Lname is an alphabetical
name so order by is going to default and assume that it should display in alphabetical sort order, so it begins with
Brown and finishes with Wilson. Please remember that the star indicates that I want every star out of column table but
the order of the results of the rows is in order of the last name column.
Below is a snapshot to further explain the functioning of the ‘Order By Cluase’
So that is the simplest way you can order results. Simply pick a column and the sql engine will figure out how to order
them and that’s true whether its alphanumeric, straight up numeric or a deep field it knows how to order those
appropriately according to the data type inside that column. You can also designate multiple columns for sub-ordering.
Imagine the same syntax we discussed above.
Mysql> select * from employees order by ST, Lname + a column name.
It’s the same select * from but now its order by ST, Lname. I have indicated two names and its separated by a coma. First
name is the state and then the last name. Now which is it going to order by and the simply answer is both. Firstly, it will
order by the state and lastly by the Lname. Here is order by state ascending in an alphanumeric order. The C’s came
before the N’s and before the T’s but within each of those orders, it took into consideration the state first and before
listing the Lname’s in an alphabetical order.
The ORDER BY statement in sql is used to sort the fetched data in either ascending or descending according to
one or more columns.
By default ORDER BY sorts the data in ascending order.
We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending
order.
Syntax of all ways of using ORDER BY is shown below:
Sort according to one column: To sort in ascending or descending order we can use the keywords ASC or
respectively.
Two important things to note here is that the default order was ascending so you can ‘DESC’ to write same statement
and you will get this
Mysql> select * from employees order by ST DESC, Fname + a column name.
So my order is the state and then followed by DESC and the first name and the results displayed ascending starting from
The T’s through N’s and finally C’s. The ascending order only applied to the column name mentioned which is ST DESC
Th Fname remained descending so the DESC only applied to the column that it was name after. If you want bot
descending then you will have to mention DESC after every column. E.g.
Mysql> select * from employees order by ST DESC, DESC Fname + a column name.
Once this is applied, it forces a descending order. You can use ASC for ascending. By default, data is listed in an AS
Format. One final point is that NULL values are considered high
The SQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that
appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that a NULL value is
different than a zero value or a field that contains spaces.
With NULL, If you sort DESC, they will appear first and ASC they will appear last.
The order by clauses allows you to chose a table inside of your columns and order the results of that select statement
and the output of same statement by that column but what if you want to order by a column that is not in your table?
I know that it doesn’t sound reasonable at first but considers EXPRESSIONS. An expression is a combination of one or
more values, operators and SQL functions that evaluate to a value. These SQL EXPRESSIONs are like formulae
and they are written in query language. You can also use them to query the database for a specific set of data.
They can be used to calculate a column that is not inside of your table. Let’s take an example of the table below. We do
have several column listed. We have total cost and project days. Imagine if we are interested in the cost per day of
each of the projects that will just be total cost divided by project days. Well, we can certainly alter the table and add a
new column, which we will add at the end and have that calculate the total cost per day, but this violates some good
practices about databases and by the way the value is a combination of the two previous fields so this only leads to
duplication. Duplicating data in a database is bad practices so the best thing to do is calculate
Project id, project name, total cost, days, total cost/days, from project order by total cost/days.
The displayed table below which is ordered by expression is imaginary and a calculated cost per day of the intended
project.
It doesn’t have to be listed in the statement and it will still display the required result but it’s only good practice to
include it. In a nutshell, Expression is a way used to calculate values of each of your roles based on other existing
columns inside of your table.
Aliases are the temporary names given to table or column for the purpose of a particular SQL query. It is used
when name of column or table is used other than their original names, but the modified name is only
temporary
• Aliases are created to make table or column names more readable.
• The renaming is just a temporary change and table name does not change in the original database
• Aliases are useful when table or column names are big or not very readable.
• These are preferred when there are more than one table involved in a query.
They are user friendly with expressions. You temporarily rename a column and order your data by that name.
The diagram below explains further. Please note that both expressions and aliases evaporate after using them
to call your statements and can only be reused if saved it within your database.
NOTE: below is the diagram.
Other important point to note. You can use double-quotes for your aliases that includes spaces. You can also order by
Number of day DESC. Examples are listed below
The essential capabilities of SELECT statement are Selection, Projection and Joining. Displaying specific
columns from a
table is known as a project operation. We will now focus on displaying specific rows of output. This is known
as a
select operation. Specific rows can be selected by adding a WHERE clause to a SELECT query. As a matter of
fact, the
WHERE clause appears just after the FROM clause in SELECT query hierarchy. The sequence has to be
maintained in
all scenarios. If violated, Oracle raises an exception.
Every database usually contains a large amount of data in it. Even if it’s a small database in an organization, it will still
run thousands of rows within the database primary tables so when one is querying or sorting data from the database,
It is important to filter out those results and limit the number of rows. Afterall it’s not easy to get through a large
number of rows when querying your data so an effective way to do this is to enter or apply the where clause
statement. This is like how one can use the where clause in one’s update statement to limit the numbers of rows that
are affected by your statements, in this case the statement is just looking or returning the value for us but the where
clause will limit the query. For example:
Mysql> SELECT emp_id, Fname, Lname, st, startdate FROM employees WHERE employee_id > 3;
The WHERE CLAUSE is used to limit results from your select queries. It can get really complicated. It has a lot of features
That one can use, and the oracle exam will be focused on the different ways to use the WHERE CLAUSE.
The where clause defines the search condition of an SQL statement, and it thus falls into the core functional
domain of an index: finding data quickly.
Although the where clause has a huge impact on performance, it is often phrased carelessly so that the database
has to scan a large part of the index. The result: a poorly written where clause is the first ingredient of a slow query.
Another very important point to note here is that I have been wrapping my dates and my strings with a single
quote. This is important and we call them date and strings ‘LITERALS’ It is important to differentiate the text
from the strings from a column name or a key word so if I have Lname = ‘finkel’. This will be the most
appropriate way to filter the information on the last name and will be displayed in the diagram below. There
are wrong ways to do as also displayed in the diagram below. The last example is correct because numbers
don’t need a string.
The WHERE CLAUSE in oracle is the LIKE operator. LIKE is used to perform a wildcard comparison.
Wildcard card comparison can also be thought of as partial comparison. So instead of saying, is X = Y, one will
say does X match a pattern of Y. One can describe Y using wildcards. It will be easier if one looks at it in
action. The diagram below will explain further.
‘ja%’. This will only display any name with Ja but ‘j%’ will display all names that begins with J.
The underscores (_) represent one and only one character and percentage (%) represent zero and more
characters. These two very easy wildcards characters to use.
These three operators are used for the most common aspects of Boolean logic. Regardless of which operator
is used the result always boils down to one of two outcomes: TRUE or FALSE. Where clauses become really
interesting when we consider combining more than one field to filter a result. For instance, using our sample
database as an example, we may want to find large orders, such as those with a quantity greater than 10 and
price greater than $5.00. This could be written as
A common multiple test will be AND/OR. Any output results in the example below will have to end up in the
display will have to meet up with both standards as stated below in the logical operations.
It’s important to know that you do not have to match columns data types when using
Boolean logic in the where clause through out Boolean operation. E.g.
Please note that the syntax wants info about Fname = ‘Amy’ OR Lname LIKE ‘W%’. This statement
will display the required info as long as one of them is correct.
Using the ‘NOT’ key words. This is essentially to reverse and expression
It can be used as not greater or less than.
Boolean operators in the order of precedence
The above is how they should be written.
WHERE ST =‘CA’
OR ST = ‘NY’
AND STARTDATE > ‘01/01/2016
In order to get the results the way Boolean operates then we have to include parentheses.
The acronyms to remember Boolean order will be.
PARENTHESES > Please
NOT > Never order
AND > Argue
OR> Order
argue
Using the IN, BETWEEN and IS comparators. These are nonstandard operators. It can be very confusing at
first, but one should get familiar with it as time goes on.
The first two are used to replace a more verbal syntax. They don’t do anything special. An example will be
In both statements above. ‘IN’ is just used to replace ‘=‘
They are used simply for eligibility so the syntax above can accommodate more states e.g. ‘CA’,
‘NY’, ‘NJ’, ‘MI’ and so on.
One can also replace the ‘IN’ with the ‘OR’ statements
Some of the rules about these parentheses are required. They use numbers, dates and characters. The dates
must match with the column so as a rule, one must be careful when filling out the date columns
Adding a ‘NOT’ to the statements changes the output. It will then display states outside of the mentioned one
in the original statement. In this case ‘TX’
One can use BETWEEN to replace the combination of less than <= and >= is used to replace
As shown above, BETWEEN is used to replace the lesser and greater than column. It doesn’t have more
advantage. They are both equivalent to one another and you can use either interchangeable.
The rules of the BETWEENS:
It will do all of the above first and note that lower values are inserted before higher ones.
Finally we use IS or IS NOT to compare against NULL values. The NULL values are weird in every database.
They are not blank they are not zeros but in their own value. A value that was never specified so as a result we
have to treat them differently.
As shown above = is not the correct thing to use. IS will perfectly do the job. Using the IS NOT operator then you
can do this.
Limiting results with the fetch clause:
There is a powerful little clause in a select statement called the FETECH clause. It is used just like the WHERE
clause to limit results and limit the number of query that is returned but with one critical difference, whereas
WHERE filters your data values based on where date is after some time and numbers greater than certain
values. Fetch limits your results based on your data size. E.g.
As shown on the diagram above, fetch is limited to the first 5 rows of the database. Selecting data from a
database using the fetch clause points directly to the number of rows your query wants. There are other
options that can be used like NEXT which will replace FIRST and ROWS which can also be written as ROW
without the S. Neither of those will ever impact the statement at all.
One other important thing one should know is that adding more rows than we have on the on the database
table structure, The results will return without an error. In fact it will return all the rows on the table as shown
below
Aside from limiting the number of rows using the fetch clause, you can also limit the percentage of rows
instead as show in the diagram below.
As shown the query will only display 25 percent of the row on the table. In this case, 25% of 10 rows is 2.5%.
The data base can not display 2.5 so it will display a result close to the answer as shown below.
The one complication inside of the fetch clause is that only key word which can be replaced with TIES. It
include all “Tied” values and only applies when an ORDER BY clause is included.
ORDER BY ST, first selected all CA’s and picked one NY randomly to complete the query.
Conversely, if you change that with TIE, you will get a different behavior. E.g.
The output displays 60% with all the other ties which are the NY.
Ampersand substitution is a way to parameterize your queries and it is an *only* SQL*Plus utility tool. It is used
to write queries sql plus and not available in most programs. It can be used anywhere in the syntax and it will
deliver results.
Substitution variables allow you to write generic SQL*Plus scripts. They allow you to mark places in a script
where you want to substitute values at runtime. A substitution variable is the same thing as a user variable.
SQL*Plus also allows you to place user variables in your script to mark places where you want to supply a value
at runtime. When you use them this way, they are called substitution variables.
A substitution variable is not like a true variable used in a programming language. Instead, a substitution
variable marks places in the text where SQL*Plus does the equivalent of a search and replace at runtime,
replacing the reference to a substitution variable with its value.
Substitution variables are set off in the text of a script by preceding them with either one or two ampersand
One needs to consider quotes when using it with a text value. In the diagram below, the first syntax is wrong
because BEN wasn’t surrounded by a single quote, so it gave a result with an error. The second one is correct.
You can prompt the user with the substitution variables and can also set it ahead of time using the DEFINE
command inside the script. I can run my statement with the DEFINE command, select and the ampersand to
give a correct output. It is important to know that set ampersand usually last for a session. You can undefine it
with the command in the diagram. See diagram below.
Finally I want to look at the SHOW and SET commands to view and update SQL*PLUS in the system
properties. The SHOW command is used to show verifiers and the SET is to turn on and off a verifier as shown
below.
When you are working with ampersand variables substitutions inside of the SQL*PLUS utility, there are some
additional features that you want to check out so that you can take full advantage of these functionalities.
Those features are PROMPT, ACCEPT and DEFINE. Prompt and accept are kind of inter-related. Prompt is
used to display output to the user without functionality.
The diagram show that prompt produced the first line of a script that contains no directions you might need
but remember that you can build a script and save it to a text file and then just execute that whole script by
referencing that file inside of SQL*PLUS so if you do that you can use prompt to put directions on top of your
script, especially if it a large one. Prompts can be used to provide a list of directions, instructions and
communications to whom ever is executing the script file.
ACCEPT: goes hand in hand with prompt. It is used to collect keyboard input from the user and store it in a
substitution variable. The only major difference between both is that in this case you can use some verbose
content or language.
Please note that running the above statement is same as defining the variables inside of sql plus. These variables
can be turned on and off. By default, it stops working after each session.
The last one is called the DEFINE system property. This is used to turn system variables ON/OFF with a set
command. It is also used to set or store variable inside of a system. What’s the advantage of turning off system
variables?
Ben Finkel- Using the order by clause.pptx

More Related Content

Similar to Ben Finkel- Using the order by clause.pptx

SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersBRIJESH KUMAR
 
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDev Chauhan
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functionsVikas Gupta
 
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsgADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsgzmulani8
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standardsAlessandro Baratella
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
Dbms question
Dbms questionDbms question
Dbms questionRicky Dky
 
Advanced Database Systems - Presentation 3.pptx
Advanced Database Systems - Presentation 3.pptxAdvanced Database Systems - Presentation 3.pptx
Advanced Database Systems - Presentation 3.pptxEllenGracePorras
 
Intro to tsql unit 1
Intro to tsql   unit 1Intro to tsql   unit 1
Intro to tsql unit 1Syed Asrarali
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxjainendraKUMAR55
 
Intro To TSQL - Unit 1
Intro To TSQL - Unit 1Intro To TSQL - Unit 1
Intro To TSQL - Unit 1iccma
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasadpaddu123
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasadpaddu123
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Techglyphs
 
98765432345671223Intro-to-PostgreSQL.ppt
98765432345671223Intro-to-PostgreSQL.ppt98765432345671223Intro-to-PostgreSQL.ppt
98765432345671223Intro-to-PostgreSQL.pptHastavaramDineshKuma
 

Similar to Ben Finkel- Using the order by clause.pptx (20)

SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for Developers
 
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
 
Sql DML
Sql DMLSql DML
Sql DML
 
Sql DML
Sql DMLSql DML
Sql DML
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsgADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
1 introduction to my sql
1 introduction to my sql1 introduction to my sql
1 introduction to my sql
 
Dbms question
Dbms questionDbms question
Dbms question
 
SQL
SQLSQL
SQL
 
Advanced Database Systems - Presentation 3.pptx
Advanced Database Systems - Presentation 3.pptxAdvanced Database Systems - Presentation 3.pptx
Advanced Database Systems - Presentation 3.pptx
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Intro to tsql unit 1
Intro to tsql   unit 1Intro to tsql   unit 1
Intro to tsql unit 1
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
 
Intro To TSQL - Unit 1
Intro To TSQL - Unit 1Intro To TSQL - Unit 1
Intro To TSQL - Unit 1
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasad
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasad
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2
 
98765432345671223Intro-to-PostgreSQL.ppt
98765432345671223Intro-to-PostgreSQL.ppt98765432345671223Intro-to-PostgreSQL.ppt
98765432345671223Intro-to-PostgreSQL.ppt
 

Recently uploaded

Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024thyngster
 
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝DelhiRS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhijennyeacort
 
vip Sarai Rohilla Call Girls 9999965857 Call or WhatsApp Now Book
vip Sarai Rohilla Call Girls 9999965857 Call or WhatsApp Now Bookvip Sarai Rohilla Call Girls 9999965857 Call or WhatsApp Now Book
vip Sarai Rohilla Call Girls 9999965857 Call or WhatsApp Now Bookmanojkuma9823
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationshipsccctableauusergroup
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort servicejennyeacort
 
9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home ServiceSapana Sha
 
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...limedy534
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsappssapnasaifi408
 
20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdfHuman37
 
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...ThinkInnovation
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts ServiceSapana Sha
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...soniya singh
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Sapana Sha
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]📊 Markus Baersch
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 
ASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel CanterASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel Cantervoginip
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFAAndrei Kaleshka
 

Recently uploaded (20)

Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
 
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝DelhiRS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
 
vip Sarai Rohilla Call Girls 9999965857 Call or WhatsApp Now Book
vip Sarai Rohilla Call Girls 9999965857 Call or WhatsApp Now Bookvip Sarai Rohilla Call Girls 9999965857 Call or WhatsApp Now Book
vip Sarai Rohilla Call Girls 9999965857 Call or WhatsApp Now Book
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
 
9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service
 
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
 
20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf
 
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts Service
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 
ASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel CanterASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel Canter
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFA
 

Ben Finkel- Using the order by clause.pptx

  • 1. BEN FINKEL CBT NUGGET ON USING THE ‘ORDER BY CLAUSE’ A SUMMARY BY SAMUEL UKWESA
  • 2.
  • 3. When inserting , inputting or appending data into a database, it is usually done in an uninteresting manner. It may be done in a manner that it came in source files or any other way through which it came into your system. This also depend on the various ways through which people key in those data. There are different ways through which data is stored. Consequently, when you select and query the data on the database then the such data is not especially useful. We can use the ‘order by clause’ inside of DMS to rearrange the order of the output from the data that we see from a select statement. Consider the table below, it is an employees table that I fill out with ten different role and a bunch of other data in it. Well I can use the ‘‘order by clause’’ to re- order those results when I order them from the table for example, if I run this command. Mysql> select * from employees order by Lname + a colume name. This will display the results below in an alphabetical order based on the column name because Lname is an alphabetical name so order by is going to default and assume that it should display in alphabetical sort order, so it begins with Brown and finishes with Wilson. Please remember that the star indicates that I want every star out of column table but the order of the results of the rows is in order of the last name column. Below is a snapshot to further explain the functioning of the ‘Order By Cluase’
  • 4.
  • 5. So that is the simplest way you can order results. Simply pick a column and the sql engine will figure out how to order them and that’s true whether its alphanumeric, straight up numeric or a deep field it knows how to order those appropriately according to the data type inside that column. You can also designate multiple columns for sub-ordering. Imagine the same syntax we discussed above. Mysql> select * from employees order by ST, Lname + a column name. It’s the same select * from but now its order by ST, Lname. I have indicated two names and its separated by a coma. First name is the state and then the last name. Now which is it going to order by and the simply answer is both. Firstly, it will order by the state and lastly by the Lname. Here is order by state ascending in an alphanumeric order. The C’s came before the N’s and before the T’s but within each of those orders, it took into consideration the state first and before listing the Lname’s in an alphabetical order. The ORDER BY statement in sql is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order. Syntax of all ways of using ORDER BY is shown below: Sort according to one column: To sort in ascending or descending order we can use the keywords ASC or respectively.
  • 6.
  • 7. Two important things to note here is that the default order was ascending so you can ‘DESC’ to write same statement and you will get this Mysql> select * from employees order by ST DESC, Fname + a column name. So my order is the state and then followed by DESC and the first name and the results displayed ascending starting from The T’s through N’s and finally C’s. The ascending order only applied to the column name mentioned which is ST DESC Th Fname remained descending so the DESC only applied to the column that it was name after. If you want bot descending then you will have to mention DESC after every column. E.g. Mysql> select * from employees order by ST DESC, DESC Fname + a column name. Once this is applied, it forces a descending order. You can use ASC for ascending. By default, data is listed in an AS Format. One final point is that NULL values are considered high The SQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank. A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces.
  • 8. With NULL, If you sort DESC, they will appear first and ASC they will appear last.
  • 9.
  • 10. The order by clauses allows you to chose a table inside of your columns and order the results of that select statement and the output of same statement by that column but what if you want to order by a column that is not in your table? I know that it doesn’t sound reasonable at first but considers EXPRESSIONS. An expression is a combination of one or more values, operators and SQL functions that evaluate to a value. These SQL EXPRESSIONs are like formulae and they are written in query language. You can also use them to query the database for a specific set of data. They can be used to calculate a column that is not inside of your table. Let’s take an example of the table below. We do have several column listed. We have total cost and project days. Imagine if we are interested in the cost per day of each of the projects that will just be total cost divided by project days. Well, we can certainly alter the table and add a new column, which we will add at the end and have that calculate the total cost per day, but this violates some good practices about databases and by the way the value is a combination of the two previous fields so this only leads to duplication. Duplicating data in a database is bad practices so the best thing to do is calculate Project id, project name, total cost, days, total cost/days, from project order by total cost/days. The displayed table below which is ordered by expression is imaginary and a calculated cost per day of the intended project.
  • 11. It doesn’t have to be listed in the statement and it will still display the required result but it’s only good practice to include it. In a nutshell, Expression is a way used to calculate values of each of your roles based on other existing columns inside of your table.
  • 12. Aliases are the temporary names given to table or column for the purpose of a particular SQL query. It is used when name of column or table is used other than their original names, but the modified name is only temporary • Aliases are created to make table or column names more readable. • The renaming is just a temporary change and table name does not change in the original database • Aliases are useful when table or column names are big or not very readable. • These are preferred when there are more than one table involved in a query. They are user friendly with expressions. You temporarily rename a column and order your data by that name. The diagram below explains further. Please note that both expressions and aliases evaporate after using them to call your statements and can only be reused if saved it within your database. NOTE: below is the diagram.
  • 13.
  • 14. Other important point to note. You can use double-quotes for your aliases that includes spaces. You can also order by Number of day DESC. Examples are listed below
  • 15.
  • 16. The essential capabilities of SELECT statement are Selection, Projection and Joining. Displaying specific columns from a table is known as a project operation. We will now focus on displaying specific rows of output. This is known as a select operation. Specific rows can be selected by adding a WHERE clause to a SELECT query. As a matter of fact, the WHERE clause appears just after the FROM clause in SELECT query hierarchy. The sequence has to be maintained in all scenarios. If violated, Oracle raises an exception. Every database usually contains a large amount of data in it. Even if it’s a small database in an organization, it will still run thousands of rows within the database primary tables so when one is querying or sorting data from the database, It is important to filter out those results and limit the number of rows. Afterall it’s not easy to get through a large number of rows when querying your data so an effective way to do this is to enter or apply the where clause statement. This is like how one can use the where clause in one’s update statement to limit the numbers of rows that are affected by your statements, in this case the statement is just looking or returning the value for us but the where clause will limit the query. For example: Mysql> SELECT emp_id, Fname, Lname, st, startdate FROM employees WHERE employee_id > 3;
  • 17. The WHERE CLAUSE is used to limit results from your select queries. It can get really complicated. It has a lot of features That one can use, and the oracle exam will be focused on the different ways to use the WHERE CLAUSE.
  • 18. The where clause defines the search condition of an SQL statement, and it thus falls into the core functional domain of an index: finding data quickly. Although the where clause has a huge impact on performance, it is often phrased carelessly so that the database has to scan a large part of the index. The result: a poorly written where clause is the first ingredient of a slow query.
  • 19. Another very important point to note here is that I have been wrapping my dates and my strings with a single quote. This is important and we call them date and strings ‘LITERALS’ It is important to differentiate the text from the strings from a column name or a key word so if I have Lname = ‘finkel’. This will be the most appropriate way to filter the information on the last name and will be displayed in the diagram below. There are wrong ways to do as also displayed in the diagram below. The last example is correct because numbers don’t need a string.
  • 20.
  • 21. The WHERE CLAUSE in oracle is the LIKE operator. LIKE is used to perform a wildcard comparison. Wildcard card comparison can also be thought of as partial comparison. So instead of saying, is X = Y, one will say does X match a pattern of Y. One can describe Y using wildcards. It will be easier if one looks at it in action. The diagram below will explain further. ‘ja%’. This will only display any name with Ja but ‘j%’ will display all names that begins with J.
  • 22. The underscores (_) represent one and only one character and percentage (%) represent zero and more characters. These two very easy wildcards characters to use.
  • 23.
  • 24. These three operators are used for the most common aspects of Boolean logic. Regardless of which operator is used the result always boils down to one of two outcomes: TRUE or FALSE. Where clauses become really interesting when we consider combining more than one field to filter a result. For instance, using our sample database as an example, we may want to find large orders, such as those with a quantity greater than 10 and price greater than $5.00. This could be written as A common multiple test will be AND/OR. Any output results in the example below will have to end up in the display will have to meet up with both standards as stated below in the logical operations.
  • 25. It’s important to know that you do not have to match columns data types when using Boolean logic in the where clause through out Boolean operation. E.g. Please note that the syntax wants info about Fname = ‘Amy’ OR Lname LIKE ‘W%’. This statement will display the required info as long as one of them is correct.
  • 26. Using the ‘NOT’ key words. This is essentially to reverse and expression It can be used as not greater or less than.
  • 27. Boolean operators in the order of precedence The above is how they should be written. WHERE ST =‘CA’ OR ST = ‘NY’ AND STARTDATE > ‘01/01/2016
  • 28. In order to get the results the way Boolean operates then we have to include parentheses. The acronyms to remember Boolean order will be. PARENTHESES > Please NOT > Never order AND > Argue OR> Order argue
  • 29.
  • 30. Using the IN, BETWEEN and IS comparators. These are nonstandard operators. It can be very confusing at first, but one should get familiar with it as time goes on. The first two are used to replace a more verbal syntax. They don’t do anything special. An example will be In both statements above. ‘IN’ is just used to replace ‘=‘ They are used simply for eligibility so the syntax above can accommodate more states e.g. ‘CA’, ‘NY’, ‘NJ’, ‘MI’ and so on. One can also replace the ‘IN’ with the ‘OR’ statements
  • 31. Some of the rules about these parentheses are required. They use numbers, dates and characters. The dates must match with the column so as a rule, one must be careful when filling out the date columns Adding a ‘NOT’ to the statements changes the output. It will then display states outside of the mentioned one in the original statement. In this case ‘TX’
  • 32. One can use BETWEEN to replace the combination of less than <= and >= is used to replace As shown above, BETWEEN is used to replace the lesser and greater than column. It doesn’t have more advantage. They are both equivalent to one another and you can use either interchangeable.
  • 33. The rules of the BETWEENS: It will do all of the above first and note that lower values are inserted before higher ones. Finally we use IS or IS NOT to compare against NULL values. The NULL values are weird in every database. They are not blank they are not zeros but in their own value. A value that was never specified so as a result we have to treat them differently.
  • 34. As shown above = is not the correct thing to use. IS will perfectly do the job. Using the IS NOT operator then you can do this.
  • 35.
  • 36.
  • 37. Limiting results with the fetch clause: There is a powerful little clause in a select statement called the FETECH clause. It is used just like the WHERE clause to limit results and limit the number of query that is returned but with one critical difference, whereas WHERE filters your data values based on where date is after some time and numbers greater than certain values. Fetch limits your results based on your data size. E.g. As shown on the diagram above, fetch is limited to the first 5 rows of the database. Selecting data from a database using the fetch clause points directly to the number of rows your query wants. There are other options that can be used like NEXT which will replace FIRST and ROWS which can also be written as ROW without the S. Neither of those will ever impact the statement at all.
  • 38. One other important thing one should know is that adding more rows than we have on the on the database table structure, The results will return without an error. In fact it will return all the rows on the table as shown below
  • 39. Aside from limiting the number of rows using the fetch clause, you can also limit the percentage of rows instead as show in the diagram below. As shown the query will only display 25 percent of the row on the table. In this case, 25% of 10 rows is 2.5%. The data base can not display 2.5 so it will display a result close to the answer as shown below.
  • 40. The one complication inside of the fetch clause is that only key word which can be replaced with TIES. It include all “Tied” values and only applies when an ORDER BY clause is included. ORDER BY ST, first selected all CA’s and picked one NY randomly to complete the query.
  • 41. Conversely, if you change that with TIE, you will get a different behavior. E.g. The output displays 60% with all the other ties which are the NY.
  • 42.
  • 43. Ampersand substitution is a way to parameterize your queries and it is an *only* SQL*Plus utility tool. It is used to write queries sql plus and not available in most programs. It can be used anywhere in the syntax and it will deliver results. Substitution variables allow you to write generic SQL*Plus scripts. They allow you to mark places in a script where you want to substitute values at runtime. A substitution variable is the same thing as a user variable. SQL*Plus also allows you to place user variables in your script to mark places where you want to supply a value at runtime. When you use them this way, they are called substitution variables. A substitution variable is not like a true variable used in a programming language. Instead, a substitution variable marks places in the text where SQL*Plus does the equivalent of a search and replace at runtime, replacing the reference to a substitution variable with its value. Substitution variables are set off in the text of a script by preceding them with either one or two ampersand
  • 44. One needs to consider quotes when using it with a text value. In the diagram below, the first syntax is wrong because BEN wasn’t surrounded by a single quote, so it gave a result with an error. The second one is correct.
  • 45. You can prompt the user with the substitution variables and can also set it ahead of time using the DEFINE command inside the script. I can run my statement with the DEFINE command, select and the ampersand to give a correct output. It is important to know that set ampersand usually last for a session. You can undefine it with the command in the diagram. See diagram below.
  • 46. Finally I want to look at the SHOW and SET commands to view and update SQL*PLUS in the system properties. The SHOW command is used to show verifiers and the SET is to turn on and off a verifier as shown below.
  • 47.
  • 48. When you are working with ampersand variables substitutions inside of the SQL*PLUS utility, there are some additional features that you want to check out so that you can take full advantage of these functionalities. Those features are PROMPT, ACCEPT and DEFINE. Prompt and accept are kind of inter-related. Prompt is used to display output to the user without functionality. The diagram show that prompt produced the first line of a script that contains no directions you might need but remember that you can build a script and save it to a text file and then just execute that whole script by referencing that file inside of SQL*PLUS so if you do that you can use prompt to put directions on top of your script, especially if it a large one. Prompts can be used to provide a list of directions, instructions and communications to whom ever is executing the script file. ACCEPT: goes hand in hand with prompt. It is used to collect keyboard input from the user and store it in a substitution variable. The only major difference between both is that in this case you can use some verbose content or language.
  • 49. Please note that running the above statement is same as defining the variables inside of sql plus. These variables can be turned on and off. By default, it stops working after each session.
  • 50. The last one is called the DEFINE system property. This is used to turn system variables ON/OFF with a set command. It is also used to set or store variable inside of a system. What’s the advantage of turning off system variables?