Oracle interview questions sorting

Table of contents

Oracle interview questions sorting

1. The difference between MySQL and Oracle:

2. What is the difference between function and procedure in Oracle? 

3. Compare truncate and delete commands? 

4. Definition of rowid and rownum in oralce 

5. What are the characteristics of transactions (ACID)?

6. List several table join methods

7. Describe the relationship between tablespace and datafile in oracle

8. What is logical backup

9. What is a physical backup

10. What are the usage methods and differences between NVL and NVL2 functions?

11. The difference between union and union all

12. The difference between minus and intersect

13. What is a stored procedure and what are its advantages?

14. What is the three paradigms

15. What is a view? And what are the usage scenarios of the view?

16. What is an index? What is the role and advantages and disadvantages?

17. What are optimistic locks and pessimistic locks in the database?

18. Database structure optimization 1) Paradigm optimization:

 19. Explain the cursor in oralce

20. Describe triggers in oracle

21. Use oracle pseudo columns to delete duplicate records in the table: 

22. List the names of all employees and the names of their immediate supervisors.

23. List all employees whose employment date predates their immediate supervisor.

24. List various jobs with a minimum salary greater than 1500.

25. List the annual salary of all employees, sorted by annual salary from low to high. 

26. List all employees who do the same job as "SCOTT".

27. Delete the employee with the highest salary in department 10.

28. Cut the salary of the highest paid employees by 30%.

29. Show the job title of the highest paid person.

30. Query employee name, salary and salary level (salary>=3000 is level 3, salary>2000 is level 2, salary<=2000 is level 1)

31.语法:case … when … then … when … then … else … end

32. Pagination in Oracle

33. A table called department has only one field name, and there are 4 records in total, which are a, b, c, and d, corresponding to four ball pairs. Now the four ball pairs are competing, and a sql statement is used to display all Possible match combinations.


Oracle interview questions sorting

1. The difference between MySQL and Oracle:

  1. MySQL is an open source project, free of charge. MySQL is the first choice for small and medium-sized enterprises. Oracle is a mature database product launched by Oracle.
  2. The difference in SQL syntax, MySQL is more flexible, and Oracle is more strict (specifically, single quotation marks, pagination processing, and automatic growth of primary keys)
  3. Support for transactions. MySQL does not support transactions by default, only the storage engine innodb supports them. Oracle fully supports transactions.
  4. concurrency. MySql defaults to table-level locks, and Oracle row-level locks, so Oracle's parallel issuance is much higher.

2. What is the difference between function and procedure in  Oracle ?

1). Function function is a kind of stored procedure. 
2). The function can have no parameters, but it must have a return value. The stored procedure can have no parameters and does not need to return a value. 
3). Return values ​​through out parameters, if you need to return multiple parameters, it is recommended to use stored procedures 
4). In SQL data manipulation statements, only functions can be called and stored procedures cannot be called

 3. Compare truncate and delete commands? 


1). Both truncate and delete can delete data entities. The operation of truncate is not recorded in the rollback log, so the operation speed is faster, but at the same time, the data cannot be recovered. 2). The delete operation does not free up space in the table space 

) . Truncate cannot delete views, etc. 
4). Truncate is a data definition language (DDL), while delete is a data manipulation language (DML) 

4. Definition of rowid and rownum in  oralce

1). rowid and rownum are both pseudo-columns 
2). rowid is a physical address, used to locate the physical storage location of specific data in oracle 
3). rownum is the output result sorting of sql

5. What are the characteristics of transactions (ACID)?

A transaction is a series of operations performed as a logical unit, and a logical unit of work must have four properties, called ACID (atomicity, consistency, isolation, and durability) properties.

1) Atomicity (Atomic): All operations in the transaction must be done or not done at all. The failure of any operation will lead to the failure of the entire transaction.

2) Consistency: The system state is the same after the transaction ends

3) Isolation (Isolated): Concurrently executed transactions cannot see each other's intermediate state

4) Durable (Durable): After the transaction is completed, even if a catastrophic failure occurs, the data can be reconstructed after the failure through log and synchronous backup

6. List several table connection methods

Equivalent join (inner join), non-equal join, self join, outer join (left, right, full)

Inner join, also known as equivalence join, filters rows that match exactly

The left join is mainly based on the left table. In addition to filtering the rows that match exactly, it will also filter the rows that do not match in the left table. If no matching data is found, fill it with null

The right join is based on the right table. In addition to filtering the rows that match exactly, it will also select the rows that do not match in the table. If no matching data is found, fill it with null

  7. Describe the relationship between tablespace and datafile in oracle


A tablespace can contain one or more datafiles. The table space expands the table space by adding or extending the data file, and the size of the table space is the sum of the size of the data files that make up the table space. A datafile can only belong to one tablespace; a tablespace can have one or more datafiles, and each datafile can only be in one tablespace. The data in the table is distributed among the datafiles in the tablespace through the hash algorithm. The tablespace is logical The concept of datafile physically stores various objects of the database.

   8. What is logical backup

1) Logical backup (exp/imp) is used to restore database objects. But not based on point-in-time fully recoverable backup strategies. It can only be used as a supplement to online backup and offline backup.
2) Complete logical backup
The complete logical backup is to export the entire database into a database format file, which can be transplanted among different database versions, operating systems and hardware platforms.
3) Logical backup of specified table
The specified database table can be backed up through the backup tool, which can avoid the waste of time and financial resources caused by complete logical backup.

9. What is a physical backup


Physical backup is the main backup method. It is used to ensure that the database is restored with minimal database loss or no data loss. Physical backups are divided into hot backups and cold backups

  1) Hot backup: mainly means that the backup process is performed when the database is open and the user can use it. The situations that need to perform hot physical backup are: because the nature of the database requires uninterrupted work, only hot physical backup can be used at this time.

2) Cold backup: Cold physical backup provides the simplest and most direct method to protect the database from being lost due to physical damage.

For a database that already has the largest amount of data, the database can be shut down at night, and cold physics is applied at this time.

When upgrading the database server (such as replacing the hard disk), it is necessary to back up the database information and use cold backup.

10. What are the usage methods and differences between NVL and NVL2 functions?

1 ) NVL (expr1, expr2): if expr1 is NULL, return expr2; if it is not NULL, return expr1. Note that the types of the two must be consistent
2 ) NVL2 (expr1, expr2, expr3): expr1 is not NULL. Returns expr2; if NULL, returns expr3. If expr2 and expr3 are of different types. expr3 will be converted to the type of expr2 

11. The difference between union and union all

1) UNION : It consists of all non-repeated rows selected by each query. The union does not include repeated values, and it is sorted in ascending order by the first column of the first query by default.

2) UNION ALL : All rows selected by each query. Exact unions include repeated values. Not sorted.

12. The difference between minus and intersect

     1 ) MINUS: Rows in the first query but not in subsequent queries, excluding duplicate rows. Sort by column 1 of query 1 in ascending order.

2 ) INTERSECT: Take the intersection of each query result. Duplicate rows are not included. Sort by column 1 of query 1 in ascending order.

13. What is a stored procedure and what are its advantages?

Stored procedures, like functions in our programming languages, encapsulate our code (PLSQL, T-SQL). Advantages of stored procedures:

  1. Can encapsulate the code and save it in the database
  2. Let the programming language do the calling
  3. A stored procedure is a precompiled code block with high execution efficiency
  4. A stored procedure replaces a large number of T_SQL statements, which can reduce network traffic and increase communication speed

14. What is the three paradigms

First normal form: the field is the smallest unit and cannot be divided

Second normal form: To satisfy the first normal form, the fields in the table must be completely dependent on all primary keys rather than some primary keys.

Third normal form: Satisfies the second normal form, all fields other than the primary key must be independent of each other and there is no transitive dependency

15. What is a view? And what are the usage scenarios of the view?

  1. A view is a virtual table based on a data table
  2. Views are built on the basis of existing tables, and these tables on which the view is built are called base tables
  1. The statement that provides data content to the view is a SELECT statement, and the view can be understood as a stored SELECT statement
  2. Views provide users with another representation of base table data
  3. The view does not store the real data, the real data is still stored in the base table
  4. Although the programmer is operating the view, the final view will also be converted into the operation base table
  5. A base table can have 0 or more views

16. What is an index? What is the role and advantages and disadvantages?

(1) It is a mechanism for quickly querying the content in the table, similar to the directory of Xinhua Dictionary

(2) It is applied to certain fields in the table, but when stored, it is independent of the table

Advantages and disadvantages:

  1. Indexes speed up database retrieval
  2. Indexes reduce the speed of maintenance tasks such as insertion, deletion, and modification (although indexes can improve query speed, they can also cause performance degradation in updating data in the database system, because most data updates need to update the index at the same time)
  3. The unique index can ensure the uniqueness of each row of data. By using the index, the optimization hider can be used in the query process to improve the performance of the system
  4. Indexes require physical and data space

17. What are optimistic locks and pessimistic locks in the database?

To ensure that the isolation and unity of transactions and the unity of the database are not destroyed when multiple transactions access the same data in the database at the same time, optimistic locking and pessimistic locking are the main technical means used for concurrency control.

Pessimistic lock: Assuming that concurrency conflicts will occur, all operations that may violate data integrity are shielded. When querying data, the transaction is locked until the transaction is committed. Implementation method: use the lock mechanism in the database.

 When the select xxx for update operation is executed , the data will be locked and will only be released when commit or rollback is executed . When the select xxx for update nowait operation is executed , the data will also be locked, and when accessed by others, the ORA-00054 error may be returned, and the content is The resource is busy and needs to be handled with corresponding business measures.

Optimistic locking: Assuming that no concurrency conflicts will occur, check for data integrity violations only when committing operations. Lock the transaction when modifying data, and lock it by version. Implementation method: use version version or timestamp.

1 ): When the data is obtained, copy the entire data to the application, and compare the data in the current database with the data obtained before the update at the beginning when submitting. When the two data are found to be exactly the same, it means that there is no conflict to submit, otherwise it is a concurrent conflict, which needs to be resolved with business logic.

2) : Add a new Table Column , which adopts timestamp type and stores the time when the data was last updated. The data precision of this kind of Timestamp is the highest in Oracle 's time type, accurate to microseconds. When the update is submitted, check the timestamp of the data in the current database and compare it with the timestamp obtained before the update. If they are consistent, then OK , otherwise it is a version conflict.

18. Database structure optimization 1) Paradigm optimization:

1) such as eliminating redundancy (saving space)

2) Anti-paradigm optimization: such as adding redundancy appropriately (reducing joins)

3) Split table: vertical split and horizontal split

19. Explain the cursor in oralce

A cursor is a record locator (indicator) pointing to a result set for locating records. How to use the cursor: declare the cursor, open the cursor, extract the cursor data, close the cursor

Declare

 cursor cur is select * from category;

    record category%rowtype;

  begin

    open cur;

    loop

      fetch cur into record;

      if cur%notfound then

        exit;

      end if;

      dbms_output.put_line(to_char(record.id) || ',' || record.name);

    end loop;

    close cur;

 end;

20. Describe triggers in oracle

A trigger is a special stored procedure that is explicitly called by the user, and a trigger is when the user executes the table

Update, delete, insert are called automatically. Trigger types usually include (insert, delete, modify)

CREATE OR REPLACE TRIGGER SAL_EMP

 BEFORE UPDATE ON scott.EMP

 FOR EACH ROW

BEGIN

 IF :OLD.SAL > :NEW.SAL THEN

  DBMS_OUTPUT.PUT_LINE('工资减少');

 ELSIF :OLD.SAL < :NEW.SAL THEN

  DBMS_OUTPUT.PUT_LINE('工资增加');

 ELSE

  DBMS_OUTPUT.PUT_LINE('工资未作任何变动');

 END IF;

 DBMS_OUTPUT.PUT_LINE('更新前工资 :' || :OLD.SAL);

 DBMS_OUTPUT.PUT_LINE('更新后工资 :' || :NEW.SAL);

END;

Test code:

UPDATE scott.emp SET sal = 3000 WHERE empno = '7788';

21.  Use the oracle pseudo-column to delete duplicate records in the table: 


delete  table  t  where t.rowid not in

(select  max(t1.rowid)  from  table1 t1 where  t1.name=t.name)

According to the table structure scott.emp as shown below:

22. List the names of all employees and the names of their immediate supervisors.


Analysis: Table self-mapping, aliasing the table, and linking t1 table simulates employee table t2 to save direct superior information
select t1.ename employee name, t2.ename direct superior from emp t1,emp t2 where t1.MGR = t2.empno ;

23. List all employees whose employment date predates their immediate supervisor.


select t1.*,t2.hiredate from emp t1,emp t2 where t1.MGR = t2.empno and t1.hiredate < t2.hiredate;

24. List various jobs with a minimum salary greater than 1500.


Analysis: The minimum salary of the job——group by job, find the minimum salary
select min(sal) from emp group by job;
greater than 1500 is a grouping condition—having 
select job,min(sal) from emp group by job having min(sal ) > 1500;

25. List the annual salary of all employees, sorted by annual salary from low to high. 


select ename, sal*12 from emp order by sal*12 asc;

26. List all employees who do the same job as "SCOTT".


Analysis: first use subquery to find out the job of SCOTT: select job from emp where ename ='SCOTT';
   select * from emp where ename <> 'SCOTT' and job = (select job from emp where ename ='SCOTT');

27. Delete the employee with the highest salary in department 10.

delete from emp where deptno=10 and sal >= all(select sal from emp where deptno=10 ); // MYSQL does not support
Mysql specification, modify or delete records in the table, it is not allowed to query the same table in subquery
mysql solution : Temporary table
delete from emp where deptno=10 and sal >= all(select t.sal from (select sal from emp where deptno=10) t );

28. Cut the salary of the highest paid employees by 30%.

oracle:update emp set sal = sal*0.7 where sal = (select max(sal) from emp);
mysql:  update emp set sal = sal*0.7 where sal = (select t.maxsal  from (select max(sal) maxsal from emp) t);

29. Show the job title of the highest paid person.

select job from emp where sal = (select max(sal) from emp);
select job from emp where sal >= all(select sal from emp);

30. Query employee name, salary and salary level (salary>=3000 is level 3, salary>2000 is level 2, salary<=2000 is level 1)


analyze:

select ename,sal, case when sal>=3000 then ‘3级’ when sal>2000 then ‘2级’ else ‘1级’ end 级别 from emp;

31.语法:case … when … then … when … then … else … end

Rows and Columns Swap
Name Course Score

Zhang San language 74

Zhang San Math 83

Zhang San Physics 93

Li Si Chinese 74

Lee Si Mathematics 84

Lisi Physics 94

becomes (gets the following result):

Name Chinese Mathematics Physics

—- —- —- —-

Li Si 74 84 94

Zhang San 74 83 93

——————-

select name,max(case when cource =’语文’ then score else 0 end) from scores group by name;

select name,max(case when cource =’语文’ then score else 0 end)  语文,max(case when cource =’数学’ then score else 0 end) 数学,
max(case when cource =’英语’ then score else 0 end) 英语  from scores group by name;

32. Pagination in Oracle

  1. Use the rownum function
SELECT *

FROM (SELECT ROWNUM AS rowno,r.*

           FROM(SELECT * FROM tmp t  ORDER BY id desc

                   ) r

           where ROWNUM <= page*size

          ) a

WHERE a.rowno > (page-1)*size

  1. Use the row_number() over() function
  Select * from (

  Select * ,row_number() over(order by id desc) num

  ) a where num between (page-1)*size and page*size

33. A table called department has only one field name, and there are 4 records in total, which are a, b, c, and d, corresponding to four ball pairs. Now the four ball pairs are competing, and a sql statement is used to display all Possible match combinations.

select a.name, b.name
from team a, team b
where a.name < b.name

Guess you like

Origin blog.csdn.net/qq_55917018/article/details/128134342