Hibernate / SQL
One of the ways is to use correlated subquery to find the Nth highest salary as shown below.
SELECT name, salary FROM employee emp1 WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM Employee emp2 WHERE emp2.salary > emp1.salary)
In the above query, the 'N' may be replaced with 2 to find the second highest salary. Also for the top 2 salaries, replace the condition N-1= with N-1>=.
RANK generates the ranking within your ordered partition. Ties are assigned the same rank, with the next ranking(s) skipped. So, if you have 2 items at rank 2, the next rank listed would be ranked 4.
DENSE_RANK again gives you the ranking within your ordered partition, but the ranks are consecutive. No ranks are skipped even if there are ranks with multiple items.
NULLS are ordered at LAST for ascending order, and NULLS are ordered FIRST in case of descending order.
Extend the order by clause to include an optional NULLS FIRST or NULLS LAST clauses as shown below.
SELECT * FROM Employee ORDER BY dept_id ASC NULLS FIRST; SELECT * FROM Employee ORDER BY dept_id DESC NULLS LAST;
ROWID is the physical location of a row. It is the fastest way of locating a row, faster even than a primary key lookup. So it could be useful in certain types of transaction where we select some rows, store their ROWIDs and then later on use the ROWIDs in where clauses for DML against those same rows.
The Oracle SELECT ... FOR UPDATE syntax implicitly uses ROWID, when we update the locked row using WHERE CURRENT OF. Also the EXCEPTIONS table (referenced when applying constraints with the EXCEPTIONS INTO clause) has a column ROW_ID. This allows us to quickly identify the rows which are breaking our constraint.
For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.
You can use ROWNUM to limit the number of rows returned by a query, as in this example:
SELECT * FROM employees WHERE ROWNUM < 10;
If an ORDER BY clause follows ROWNUM in the same query, then the rows will be reordered by the ORDER BY clause. The results can vary depending on the way the rows are accessed.
SELECT * FROM employees WHERE ROWNUM < 11 ORDER BY dept;
If you embed the ORDER BY clause in a subquery and place the ROWNUM condition in the top-level query, then you can force the ROWNUM condition to be applied after the ordering of the rows. For example, the following query returns the employees with the 10 smallest employee numbers. This is sometimes referred to as top-N reporting:
SELECT * FROM (SELECT * FROM employees ORDER BY dept) WHERE ROWNUM < 11;
In a SQL database query, a correlated subquery (also known as a synchronized subquery) is a subquery (a query nested inside another query) that uses values from the outer query. Because the subquery is evaluated once for each row processed by the outer query, it can be inefficient.
The ratio of distinct values to the number of table rows. A column with only two distinct values in a million-row table would have low cardinality.
A placeholder in a SQL statement that must be replaced with a valid value or value address for the statement to execute successfully.
By using bind variables, you can write a SQL statement that accepts inputs or parameters at run time. The following example shows a query that uses v_empid as a bind variable:
SELECT * FROM employees WHERE employee_id = :v_empid;
An index organized like an upside-down tree. A B-tree index has two types of blocks: branch blocks for searching and leaf blocks that store values. The leaf blocks contain every indexed data value and a corresponding rowid used to locate the actual row. The "B" stands for "balanced" because all leaf blocks automatically stay at the same depth.
The clustered index is used to reorder the physical order of the table and search based on the key values. A table can have only one clustered index.
NonClustered Index does not alter the physical order of the table and maintains logical order of data. A table can have 999 non-clustered indexes.
Indexes are schema objects that are logically and physically independent of the data in the objects with which they are associated. Thus, an index can be dropped or created without physically affecting the table for the index.
A composite index, also called a concatenated index, is an index on multiple columns in a table. Columns in a composite index should appear in the order that makes the most sense for the queries that will retrieve data and need not be adjacent in the table.
Composite indexes can speed retrieval of data for SELECT statements in which the WHERE clause references all or the leading portion of the columns in the composite index.
Self join is often very useful to convert a hierarchical structure to a flat structure. It is used to join a table to itself as like if that is the second table.
ACID is a set of properties that you would like to apply when modifying a database.
- Atomicity,
- Consistency,
- Isolation,
- Durability.
Atomicity means that you can guarantee that all of a transaction happens, or none of it does; you can do complex operations as one single unit, all or nothing, and a crash, power failure, error, or anything else won't allow you to be in a state in which only some of the related changes have happened.
Consistency means that you guarantee that your data will be consistent; none of the constraints you have on related data will ever be violated.
Isolation means that one transaction cannot read data from another transaction that is not yet completed. If two transactions are executing concurrently, each one will see the world as if they were executing sequentially, and if one needs to read data that is written by another, it will have to wait until the other is finished.
Durability means that once a transaction is complete, it is guaranteed that all of the changes have been recorded to a durable medium (such as a hard disk), and the fact that the transaction has been completed is likewise recorded.
Candidate key is a super key from which you cannot remove any fields.
A super key is any combination of columns that uniquely identifies a row in a table.
There is NO GO statement in MySQL. Semicolon (;) at the end of each line works as GO statement in MySQL.
INSERT INTO myTable (ID) values (14);
- INNER JOIN,
- LEFT JOIN,
- RIGHT JOIN,
- OUTER JOIN,
- LEFT JOIN EXCLUDING INNER JOIN,
- RIGHT JOIN EXCLUDING INNER JOIN,
- OUTER JOIN EXCLUDING INNER JOIN.
The SQL CROSS JOIN produces a result set which is the number of rows in the first table multiplied by the number of rows in the second table, assuming no 'where' clause is used along with CROSS JOIN. This kind of result is also called as Cartesian Product. If, WHERE clause is used with CROSS JOIN, it functions like an INNER JOIN.
SELECT table112.id,table112.bval1,table112.bval2, table111.id,table111.aval1 FROM table112 CROSS JOIN table111;
The SQL SELF JOIN is used to join a table to itself as if the table were two tables, by renaming at least one table with alias in the SQL statement.
Primary key doesn't allow null while unique key allow null.
Views are virtual and the query is executed every time it is accessed.
Materialized views are disk based and are updated periodically based upon the query definition.
Using the show global status command we can determine the number of selects, updates since the last database restart. To find per day run the command now and after 24 hours and subtract the last count with the latest.
#For select SHOW GLOBAL STATUS LIKE 'Com_select'; #For update SHOW GLOBAL STATUS LIKE 'Com_update';
For INSERT and DELETE replace the query with 'Com_insert' ,'Com_delete' respectively.
Indexes may slow down inserts, deletes and updates due to locking and also costs disk space.
- Faster query execution,
- quick data retrieval,
- facilitates sorting and thus eliminate post fetch sorting strategy,
- Unique indexes uniquely identifies records in the database.
There are 2 main types.
Clustered indexes define the physical sorting of a database table rows in the storage media. Each table may have only one clustered index.
Non-clustered indexes are created outside of the database table and contain a sorted list of references to the table itself.
No. A view and table cannot have same name.
To find the second largest, Use the max aggregate function to find the largest and filter the largest value and find the maximum value again that yields the second largest.
SELECT MAX( column) FROM table WHERE column< ( SELECT MAX( column) FROM table )
Hi there, my suggestion would be using a DB sequence (or a separate table for the sequence in MYSQL DB) to generate a unique number (for example,456) and have a Database trigger (before-insert) to prefix "TCS-". This way we will make sure a unique id is generated. This solution completely relies on database objects.
if we want to achieve this using Java/hibernate, we can generate a unique number and prefix "TCS-".