Understanding SQL basics
Learning essentials of database comes as a great aid for everyone. As a developer, there are scenarios where you have to write complicated sql(structured query language) queries while implementing APIs or services. This blog provides the tools to choose the right sql queries based on the use case and keeping performance in mind. Let’s embark upon the roller-coster journey to sql mastery.
QUERIES
The queries is where it all starts. The order in which the clauses should be used are as follow: SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER BY. The where clause is used for restricting particular rows from the table whereas the having clause is used with group by to restrict the groups of rows returned from the query.
There are also aggregate functions which are used commonly in the queries like avg, count, min, max, sum. They can be used along with the group by clause to apply on each group or can be used without group by to apply on the whole table.
One relevant point to remember while dealing with aggregate functions is that regular columns cannot be selected along with columns on which aggregate functions are implemented until the query has a group by on the regular column. For example:
This query will throw an error “not a single-group group function”.
This query will work properly as the regular table column is used by group by clause.
TO_CHAR V/S TO_DATE
Every one of us at some point would have been confused of using to_char or to_date while getting our hands dirty with date types. So, lets clear the air. TO_CHAR converts numbers, dates, strings, etc to a specific format. Some sql queries and their output are given below:
Output: Rs27,000
Explanation: The L character represents local currency configured in the database. It can be different for different countries. The combinations of letters and number describes how to format the data returned from the database.
Output: 11/MAR/2020
Explanation: The to_char function displays the date type into the specified format.
When you are defining your query, TO_DATE function lets the sql know that the date is of this specified format and save it accordingly to db.
Output: 27–01–96
Output: Error as the format to be mapped to doesn’t match the data provided to the to_date function.
Performance comparison between to to_char and to_date
Below are two queries doing the same thing:
The first query is more expensive than the second query because every row’s start_date and end_date is converted into characters which is not in the second case. Also, if their is indexing on start_date and end_date, as these columns format has been changed now, cost based indexer(CBO) won’t be able to do indexing on it.
A very important point to note is when expressions are converted(i.e. NVL, COALESCE, etc) in where clause CBO will not be able to use index on that column which may lead to huge reduction in performance.
“In general, for date handling purpose like insert, update, to_date should be used. While showing the output in the preferred format, to_char should be used.”
JOINS
Another construct which comes again and again are JOINS. JOIN is use to join the table through their columns. JOIN in sql queries by default means inner join. Other joins are inner join, left join, right join and full outer join. You can join the table depending on your preference.
DML(Data manipulation language) VS DDL(Data definition language)
These are essence to writing queries ranging from simple to complex ones. Understanding DDL and DML is core to writing efficient queries. Insert, update, delete are DML transactions and create, alter, drop, truncate are DDL transactions. After DML transactions, a commit or rollback needs to be done depending on whether you want to save or not save the changes done by transaction. In DDL transactions, commit or rollback can’t be done.
Get Tarannum Khan’s stories in your inbox
Join Medium for free to get updates from this writer.
The interesting aspect is DML transactions maintains the logs, so that redoing is possible whereas in DDL transactions minimum logging is in transaction log. So DDL are performance wise faster. Lets compare two queries which are doing the same thing but the first one is a DML transaction and the second one is a DDL transaction.
The first one is slower as the DML transaction has to maintain the logs for redoing purpose. Also, Delete is executed using a row lock whereas truncate is executed using a table lock. Point to note is there can be no where clause in truncate whereas in delete where clause is possible. Truncate utilises less transaction space than delete statements.
Once you run a DML transaction on particular rows of the table, a lock is acquired for these rows. Until you commit it, the lock is not released. In between, if any other user try to access the locked rows, they won’t be able to perform their transaction and will wait for the lock to be released. It’s very important to commit once you are done with your changes, so that other apis/users hitting the same records won’t be effected.
COMPLEX QUERIES
A lot of times, subqueries are written as a part of the queries. The query within parenthesis or the sub query is executed first than the outer queries are executed. “Subqueries can reside in the FROM, WHERE or SELECT clause”. Inline query is when the subquery is in the WHERE clause. Correlated query is when the inner queries depends on the outer queries.
Correlate query example:
For these type of queries, the inner query is executed once for each row of the outer query.
INDEXES
Performance improvement discussions on databases are incomplete without indexes. The Indexes are schema objects to improve data access performance using sql queries created on specific sets of columns. Indexes can be of various types. The most common type of index is Btree. Index can be created by user by using the following query.
The picture below show a basic view how the Btree data structure stores the data.
Data is stored in the leaf blocks. Branch blocks store the range of data. Indexes should be created on those columns on which normally search is performed or the columns which are generally used in WHERE clause for those tables. On creating more indexes, the performance of the insert, update and delete is reduced as the indexes may be updated while performing these operations . For a Btree data structure, the range can be changed as more node can be added in insert or reduced in delete action in the Btree increasing the time to perform these actions. The indexes are separate objects, not specific to a table. So for a schema, each index name should be unique. On dropping or adding the indexes, the data of the table will not be effected as they are separate schema objects.
To view all the indexes of the table, this sql command is very handy.
SEQUENCES
Sequences are also schema objects to generate set of integers like 1,2,3 and so on. They are independent of the tables on which they are being used. Instead of creating sequence, identity can be created which under the hood are sequence for table. Identity are of three types:
- ID NUMBER GENERATED ALWAYS AS IDENTITY — if a user try to insert into the identity column, an error is thrown as the identity column is always generated.
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY — if a user try to insert into the identity column, no error will be thrown. If no value is passed for the identity column, it will be generated. If null is inserted into the identity column, an error will be thrown.
- ID NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY — If no value or null is inserted, a value will be generated for the identity column.
VIEWS
Views come in handy while simplifying queries. A view is a query stored as a db object. It can be accessed through other sql queries. Views acts like table but they are not as no physical space is allocated to a view. Below is the sql query to create the view
EXPLAIN PLAN
Oracle sql developer provides an amazing tool to give an in-depth analysis of the query, with processing of joins, how the index will improve the query or not. The explain plan displays the execution plan chosen by the Oracle optimiser for SELECT, UPDATE, INSERT, and DELETE statements. A statement’s execution plan is the sequence of operations Oracle performs to run the statement.
The row source tree is the key of the execution plan. It shows the following information:
- An ordering of the tables referenced by the statement
- An access method for each table mentioned in the statement
- A join method for tables affected by join operations in the statement
- Data operations like filter, sort, or aggregation
There is an icon in oracle sql developer which directly runs the explain plan for the query. If you want to use the sql statements to run the explain plan, they are:
The explain plan results let you determine whether the optimiser selects a particular execution plan, such as, nested loops join. It also helps in comprehending the optimiser decisions, such as why the optimiser chose a nested loops join instead of a hash join, and lets you understand the performance of a query, so you can tweak the query accordingly.
The above information are building blocks for writing complex and high performance query depending on the use case. Feel free to contact me at tkhaniitr@gmail.com, in case of any queries not necessarily sql ones 😀. Hope the article proves helpful.







