Design and develop with performance in mind
Establish a tuning environment
Index wisely
Reduce parsing
Take advantage of Cost Based Optimizer
Avoid accidental table scans
Optimize necessary table scans
Optimize joins
Use array processing
Consider PL/SQL for “tricky” SQL
This chapter discusses advanced SQL features including relational set operators like UNION and INTERSECT, different types of joins, subqueries, functions, views, triggers, stored procedures, cursors, and embedded SQL. It covers topics like using subqueries in the SELECT, WHERE, HAVING and FROM clauses, correlated subqueries, date/string/numeric functions, updatable views, procedural language features in PL/SQL including triggers and stored procedures, and static versus dynamic embedded SQL.
Oracle Advanced SQL and Analytic FunctionsZohar Elkayam
Even though DBAs and developers are writing SQL queries every day, it seems that advanced SQL techniques such as multidimension aggregation and analytic functions still remain relatively unknown. In this session, we will explore some of the common real-world usages for analytic function and understand how to take advantage of this great and useful tool. We will deep dive into ranking based on values and groups, understand aggregation of multiple dimensions without a group by, see how to do inter-row calculations, and much more.
This is the presentation slides which was presented in Kscope 17 on June 28, 2017.
This document provides an overview of MySQL JOIN and UNION operations. It discusses subqueries, table aliases, multi-table joins, UNION ALL, UNION rules, and GROUP BY. Subqueries allow querying data from multiple tables in a nested format. Table aliases are used to temporarily rename tables and columns for readability. JOIN operations combine data from two or more tables, including INNER JOIN, LEFT JOIN, and RIGHT JOIN. UNION combines the results of multiple SELECT statements, requiring the same number and order of columns. UNION rules specify that data types must be compatible. GROUP BY is used to retrieve aggregate information about grouped data.
El documento describe los objetos principales de JDBC para interactuar con bases de datos desde Java: Connection, Statement y ResultSet. Connection permite conectarse a la base de datos, Statement ejecuta consultas SQL y ResultSet contiene los resultados devueltos.
Design and develop with performance in mind
Establish a tuning environment
Index wisely
Reduce parsing
Take advantage of Cost Based Optimizer
Avoid accidental table scans
Optimize necessary table scans
Optimize joins
Use array processing
Consider PL/SQL for “tricky” SQL
This chapter discusses advanced SQL features including relational set operators like UNION and INTERSECT, different types of joins, subqueries, functions, views, triggers, stored procedures, cursors, and embedded SQL. It covers topics like using subqueries in the SELECT, WHERE, HAVING and FROM clauses, correlated subqueries, date/string/numeric functions, updatable views, procedural language features in PL/SQL including triggers and stored procedures, and static versus dynamic embedded SQL.
Oracle Advanced SQL and Analytic FunctionsZohar Elkayam
Even though DBAs and developers are writing SQL queries every day, it seems that advanced SQL techniques such as multidimension aggregation and analytic functions still remain relatively unknown. In this session, we will explore some of the common real-world usages for analytic function and understand how to take advantage of this great and useful tool. We will deep dive into ranking based on values and groups, understand aggregation of multiple dimensions without a group by, see how to do inter-row calculations, and much more.
This is the presentation slides which was presented in Kscope 17 on June 28, 2017.
This document provides an overview of MySQL JOIN and UNION operations. It discusses subqueries, table aliases, multi-table joins, UNION ALL, UNION rules, and GROUP BY. Subqueries allow querying data from multiple tables in a nested format. Table aliases are used to temporarily rename tables and columns for readability. JOIN operations combine data from two or more tables, including INNER JOIN, LEFT JOIN, and RIGHT JOIN. UNION combines the results of multiple SELECT statements, requiring the same number and order of columns. UNION rules specify that data types must be compatible. GROUP BY is used to retrieve aggregate information about grouped data.
El documento describe los objetos principales de JDBC para interactuar con bases de datos desde Java: Connection, Statement y ResultSet. Connection permite conectarse a la base de datos, Statement ejecuta consultas SQL y ResultSet contiene los resultados devueltos.
This is a word file for SQL COMMANDS and including some basic information regarding SQL. I hope it will help you a lot while doing SQL and its functions and commands.
Este documento proporciona una introducción a las consultas básicas en SQL Server. Explica las consultas de selección, que se utilizan para recuperar información de las bases de datos. También cubre las consultas de acción, como INSERT, UPDATE y DELETE, que se usan para agregar, modificar y eliminar registros. Por último, describe los diferentes predicados y cláusulas que se pueden usar con las consultas de selección, como SELECT, FROM, WHERE, ORDER BY y TOP.
This document outlines 8 steps to create an audit trail for the table FND_LOOKUP_VALUES in an Oracle application: 1) Find the application name, 2) Ensure audit is enabled for that application, 3) Create an audit group for the table, 4) Run a concurrent program to create audit tables and triggers, 5) Verify the audit tables were created, 6) Test the audit trail by creating new lookup data, 7) View the audit data that was captured, and 8) Optionally add more columns to the audit trail.
Este documento describe diferentes métodos para ordenar arreglos, incluyendo métodos directos como el intercambio directo, inserción directa y selección directa, así como el método avanzado de ordenación rápida (QuickSort). Define arreglos y cómo declararlos, inicializarlos y acceder a ellos. Explica cada método de ordenación con ejemplos de código.
This presentation deals with the advanced features of SQL comprising of Arithmetic Calculations, Analytical Function, PIVOT etc. Presented by Alphalogic Inc: https://www.alphalogicinc.com/
Este documento proporciona una introducción al lenguaje de consultas estructuradas SQL. Explica las cláusulas básicas SELECT, FROM y WHERE para realizar consultas simples, y cómo definir tablas, insertar, actualizar y eliminar datos. También cubre JOINs para unir tablas y obtener datos de múltiples tablas.
Una transacción es una unidad de trabajo compuesta por diversas tareas relacionadas que deben ejecutarse todas o ninguna para mantener la integridad y coherencia de los datos. Las transacciones en SQL Server se delimitan mediante instrucciones BEGIN TRANSACTION y COMMIT/ROLLBACK TRANSACTION y siguen las propiedades ACID para garantizar la atomicidad, consistencia, aislamiento y durabilidad de los datos.
Un flujo de entrada / salida (I/O stream, Input / Output stream) representa una fuente desde la
cual se reciben datos o un destino hacia el cual se envían datos. Un flujo de datos puede provenir o
dirigirse hacia archivos en disco, dispositivos de comunicaciones, otros programas o arreglos en
memoria. Los datos pueden ser bytes, tipos primitivos, caracteres propios de un idioma local, u
objetos. Los flujos pueden simplemente transferir datos sin modificación o manipular esos datos
para transformarlos de diversas maneras como parte del proceso de transferencia. Sea cual sea el
tipo de datos, un flujo se presenta como una secuencia de datos. Un flujo de entrada (input stream)
lee datos de una fuente, un item por vez. Un flujo de salida (output stream) escribe datos en un
destino, un item por vez.
The document provides an introduction to the SQL language. It discusses the three main types of SQL statements: DDL, DML, and DCL. It also covers topics such as data types, constraints, functions, views, and how to create, modify and query tables. SQL is a language used to manage relational database management systems (RDBMS) and allows users to define, manipulate, and control access to data in a RDBMS.
This document discusses advanced SQL topics including joins, subqueries, and ensuring transaction integrity. It provides examples of different types of joins like equi-joins, natural joins, outer joins, and union joins. It also discusses using subqueries in WHERE clauses, FROM clauses, and HAVING clauses, and differentiates between correlated and noncorrelated subqueries. The document concludes by defining transactions and describing SQL commands like BEGIN TRANSACTION, COMMIT, and ROLLBACK that are used to ensure transaction integrity.
This document discusses SQL constraints. It defines constraints as limitations on the type of data that can go into a table. The main types of constraints covered are:
1. Not null constraints, which enforce that a column cannot be null
2. Unique constraints, which uniquely identify each record in a table
3. Primary key constraints, which uniquely identify each record and cannot be null
4. Foreign key constraints, which link to primary keys in other tables to define relationships
5. Check constraints, which define valid value ranges for a column
6. Default constraints, which provide a default value for a column if no other value is specified.
Examples are provided for each constraint type to illustrate their syntax and usage
PL/SQL is a combination of SQL and procedural languages that enhances SQL's capabilities. It allows processing of SQL statements as a block. A PL/SQL block consists of optional declaration, mandatory execution, and optional exception sections. Variables, constants, records can be declared in the declaration section and used in the execution section. The execution section contains the main program logic. Exceptions are handled in the exception section. PL/SQL supports programming constructs like conditional statements and loops.
Creating and Managing Tables -Oracle Data base Salman Memon
After completing this lesson, you should be able to
do the following:
Describe the main database objects
Create tables
Describe the data types that can be used when specifying column definition
Alter table definitions
Drop, rename, and truncate tables
http://phpexecutor.com
Proyecto de Investigación sobre ADO.NET:
Definición, Arquitectura, Dataset, Clases de ADO.NET, EJEMPLOS.
Si quieren informarse mas sobre ADO.NET, visita mi blog aquí les dejo un link:
http://bloggerlisevelinvasquez.blogspot.pe/2017/05/ano-del-buen-servicio-alciudadano.html
The document describes shadow paging, an alternative to log-based recovery for databases. It maintains two page tables during transactions: a current page table and a shadow page table stored in non-volatile storage. This allows recovery of the pre-transaction state if needed. Shadow paging has advantages over logging like no log overhead and trivial recovery, but has higher commit overhead as many pages must be flushed. It also risks data fragmentation and requires garbage collection of old data versions after transactions.
Here are the SQL commands for the questions:
Q1: SELECT PNAME FROM PROJECT WHERE PLOCATION='Houston';
Q2: SELECT FNAME, LNAME FROM EMPLOYEE WHERE HOURS>20;
Q3: SELECT FNAME, LNAME FROM EMPLOYEE, DEPARTMENT WHERE MGRSSN=SSN;
This document discusses various SQL concepts including joins, aggregation functions, and grouping. It begins with an overview of installing MySQL Workbench and loading sample data. It then covers SELECT statements and functions like COUNT, SUM, AVG. It describes different types of joins like inner, left, right, and self joins. It provides examples of joining tables to retrieve related data and performing self joins to combine rows from the same table. It also explains how to use the GROUP BY clause to divide data into groups and apply aggregation functions.
This is a word file for SQL COMMANDS and including some basic information regarding SQL. I hope it will help you a lot while doing SQL and its functions and commands.
Este documento proporciona una introducción a las consultas básicas en SQL Server. Explica las consultas de selección, que se utilizan para recuperar información de las bases de datos. También cubre las consultas de acción, como INSERT, UPDATE y DELETE, que se usan para agregar, modificar y eliminar registros. Por último, describe los diferentes predicados y cláusulas que se pueden usar con las consultas de selección, como SELECT, FROM, WHERE, ORDER BY y TOP.
This document outlines 8 steps to create an audit trail for the table FND_LOOKUP_VALUES in an Oracle application: 1) Find the application name, 2) Ensure audit is enabled for that application, 3) Create an audit group for the table, 4) Run a concurrent program to create audit tables and triggers, 5) Verify the audit tables were created, 6) Test the audit trail by creating new lookup data, 7) View the audit data that was captured, and 8) Optionally add more columns to the audit trail.
Este documento describe diferentes métodos para ordenar arreglos, incluyendo métodos directos como el intercambio directo, inserción directa y selección directa, así como el método avanzado de ordenación rápida (QuickSort). Define arreglos y cómo declararlos, inicializarlos y acceder a ellos. Explica cada método de ordenación con ejemplos de código.
This presentation deals with the advanced features of SQL comprising of Arithmetic Calculations, Analytical Function, PIVOT etc. Presented by Alphalogic Inc: https://www.alphalogicinc.com/
Este documento proporciona una introducción al lenguaje de consultas estructuradas SQL. Explica las cláusulas básicas SELECT, FROM y WHERE para realizar consultas simples, y cómo definir tablas, insertar, actualizar y eliminar datos. También cubre JOINs para unir tablas y obtener datos de múltiples tablas.
Una transacción es una unidad de trabajo compuesta por diversas tareas relacionadas que deben ejecutarse todas o ninguna para mantener la integridad y coherencia de los datos. Las transacciones en SQL Server se delimitan mediante instrucciones BEGIN TRANSACTION y COMMIT/ROLLBACK TRANSACTION y siguen las propiedades ACID para garantizar la atomicidad, consistencia, aislamiento y durabilidad de los datos.
Un flujo de entrada / salida (I/O stream, Input / Output stream) representa una fuente desde la
cual se reciben datos o un destino hacia el cual se envían datos. Un flujo de datos puede provenir o
dirigirse hacia archivos en disco, dispositivos de comunicaciones, otros programas o arreglos en
memoria. Los datos pueden ser bytes, tipos primitivos, caracteres propios de un idioma local, u
objetos. Los flujos pueden simplemente transferir datos sin modificación o manipular esos datos
para transformarlos de diversas maneras como parte del proceso de transferencia. Sea cual sea el
tipo de datos, un flujo se presenta como una secuencia de datos. Un flujo de entrada (input stream)
lee datos de una fuente, un item por vez. Un flujo de salida (output stream) escribe datos en un
destino, un item por vez.
The document provides an introduction to the SQL language. It discusses the three main types of SQL statements: DDL, DML, and DCL. It also covers topics such as data types, constraints, functions, views, and how to create, modify and query tables. SQL is a language used to manage relational database management systems (RDBMS) and allows users to define, manipulate, and control access to data in a RDBMS.
This document discusses advanced SQL topics including joins, subqueries, and ensuring transaction integrity. It provides examples of different types of joins like equi-joins, natural joins, outer joins, and union joins. It also discusses using subqueries in WHERE clauses, FROM clauses, and HAVING clauses, and differentiates between correlated and noncorrelated subqueries. The document concludes by defining transactions and describing SQL commands like BEGIN TRANSACTION, COMMIT, and ROLLBACK that are used to ensure transaction integrity.
This document discusses SQL constraints. It defines constraints as limitations on the type of data that can go into a table. The main types of constraints covered are:
1. Not null constraints, which enforce that a column cannot be null
2. Unique constraints, which uniquely identify each record in a table
3. Primary key constraints, which uniquely identify each record and cannot be null
4. Foreign key constraints, which link to primary keys in other tables to define relationships
5. Check constraints, which define valid value ranges for a column
6. Default constraints, which provide a default value for a column if no other value is specified.
Examples are provided for each constraint type to illustrate their syntax and usage
PL/SQL is a combination of SQL and procedural languages that enhances SQL's capabilities. It allows processing of SQL statements as a block. A PL/SQL block consists of optional declaration, mandatory execution, and optional exception sections. Variables, constants, records can be declared in the declaration section and used in the execution section. The execution section contains the main program logic. Exceptions are handled in the exception section. PL/SQL supports programming constructs like conditional statements and loops.
Creating and Managing Tables -Oracle Data base Salman Memon
After completing this lesson, you should be able to
do the following:
Describe the main database objects
Create tables
Describe the data types that can be used when specifying column definition
Alter table definitions
Drop, rename, and truncate tables
http://phpexecutor.com
Proyecto de Investigación sobre ADO.NET:
Definición, Arquitectura, Dataset, Clases de ADO.NET, EJEMPLOS.
Si quieren informarse mas sobre ADO.NET, visita mi blog aquí les dejo un link:
http://bloggerlisevelinvasquez.blogspot.pe/2017/05/ano-del-buen-servicio-alciudadano.html
The document describes shadow paging, an alternative to log-based recovery for databases. It maintains two page tables during transactions: a current page table and a shadow page table stored in non-volatile storage. This allows recovery of the pre-transaction state if needed. Shadow paging has advantages over logging like no log overhead and trivial recovery, but has higher commit overhead as many pages must be flushed. It also risks data fragmentation and requires garbage collection of old data versions after transactions.
Here are the SQL commands for the questions:
Q1: SELECT PNAME FROM PROJECT WHERE PLOCATION='Houston';
Q2: SELECT FNAME, LNAME FROM EMPLOYEE WHERE HOURS>20;
Q3: SELECT FNAME, LNAME FROM EMPLOYEE, DEPARTMENT WHERE MGRSSN=SSN;
This document discusses various SQL concepts including joins, aggregation functions, and grouping. It begins with an overview of installing MySQL Workbench and loading sample data. It then covers SELECT statements and functions like COUNT, SUM, AVG. It describes different types of joins like inner, left, right, and self joins. It provides examples of joining tables to retrieve related data and performing self joins to combine rows from the same table. It also explains how to use the GROUP BY clause to divide data into groups and apply aggregation functions.
ZK is an open-source Java web framework that uses Ajax techniques to create rich internet applications (RIAs). It features a component-based model, event-driven architecture, and XML user interface markup language. ZK supports scripting languages like Java, Groovy, and Python to add interactivity on both the client- and server-side. It aims to provide a desktop-like experience within a web browser.
This document provides tips on how to become an Oracle Certified Professional (OCP). It discusses choosing a certification path, selecting exams, registering for exams, preparing for exams, and profiles of successful OCPs. Attendees can enter to win an exam voucher by leaving their business card or completing a survey.
All Oracle DBAs have to know about Unix Memory MonitoringYury Velikanov
This is one of my old presentations. I have presented it back in 2006. While most of the stuff is correct I do not exclude that it has some bugs. Let me know if you found any.
Tuyển tập 9 chuyên đề bồi dưỡng Toán lớp 5 cơ bản và nâng cao ôn thi vào lớp ...Bồi Dưỡng HSG Toán Lớp 3
Tuyển tập 9 chuyên đề bồi dưỡng Toán lớp 5 cơ bản và nâng cao ôn thi vào lớp 6 trường chuyên. Đăng ký mua tài liệu Toán 5 vui lòng liên hệ: 0948.228.325 (Zalo - Cô Trang Toán IQ).
Smartbiz_He thong MES nganh may mac_2024juneSmartBiz
Cách Hệ thống MES giúp tối ưu Quản lý Sản xuất trong ngành May mặc như thế nào?
Ngành may mặc, với đặc thù luôn thay đổi theo xu hướng thị trường và đòi hỏi cao về chất lượng, đang ngày càng cần những giải pháp công nghệ tiên tiến để duy trì sự cạnh tranh. Bạn đã bao giờ tự hỏi làm thế nào mà những thương hiệu hàng đầu có thể sản xuất hàng triệu sản phẩm với độ chính xác gần như tuyệt đối và thời gian giao hàng nhanh chóng? Bí mật nằm ở hệ thống Quản lý Sản xuất (MES - Manufacturing Execution System).
Hãy cùng khám phá cách hệ thống MES đang cách mạng hóa ngành may mặc và mang lại những lợi ích vượt trội như thế nào.
1. 1. Tối ưu hóa câu lệnh SQL
– Tối ưu hóa câu lệnh truy vấn với bảng đánh partition và index
Vấn đề: Đối với những bảng có dữ liệu lớn, khi tạo bảng người thiết kế phải thực hiện một số kỹ
thuật để tăng tốc độ truy vấn dữ liệu như đánh index, partition. Khi truy vấn người lập trình phải
tuân thủ một số nguyên tắc để đảm bảo tối ưu hóa thời gian thực hiện câu lệnh:
Không nên sử dụng hàm đối với trường đánh index, partition:
1
2
3
4
-- khong nen su dung
SELECT *
FROM users
WHERE UPPER (user_name) = UPPER ('USER_NAME');
Không nên sử dụng sử dụng toán tử not like, not in, <> với trường đánh index, partition
1
2
3
4
5
6
7
8
9
10
11
12
-- khong nen su dung
SELECT *
FROM users
WHERE user_name NOT LIKE 'USER_NAME%';
-- khong nen su dung
SELECT *
FROM users
WHERE user_name NOT IN ('USER_NAME1', 'USER_NAME2', 'USER_NAME3');
-- khong nen su dung
SELECT *
FROM users
WHERE user_name <> 'USER_NAME1';
Không nên sử dụng like ‘%str’
1
2
3
4
-- khong nen su dung
SELECT *
FROM users
WHERE user_name LIKE '%USER_NAME';
Lưu ý: Các trường hợp trên không nên sử dụng do làm mất tác dụng của cột đánh index
– Khi nào dùng IN, khi nào dùng EXISTS
Vấn đề: Trong một số trường hợp dữ liệu lớn, khi cần sử dụng toán tử IN hoặc Exists trong câu
lệnh có thể tốc độ thực thi câu lệnh khác nhau tương đối lớn. Để quyết định dùng toán tử nào ta
dựa vào đánh giá sau:
Bản chất câu lệnh khi dùng toán tử IN
2. 1
2
3
4
5
6
7
8
9
10
SELECT *
FROM t1
WHERE x IN (SELECT y
FROM t2);
--Dien giai (tuong duong voi cau lenh sau)
SELECT *
FROM t1,
(SELECT DISTINCT y
FROM t2) t2
WHERE t1.x = t2.y;
Câu lệnh này quét dữ liệu full bảng T2 khi thực hiện câu lệnh SELECT DISTINCT y FROM t2;
nếu bảng dữ liệu T2 lớn thì thời gian thực hiện câu lệnh tương đối chậm
Bản chất câu lệnh dùng Exists
1
2
3
4
5
6
7
for x in ( select * from t1 )
loop
if ( exists ( select null from t2 where y = x.x ))
then
OUTPUT THE RECORD
end if
end loop;
Câu lệnh này quét dữ liệu full bảng T1, trường hợp bảng T2 đánh index theo trường y thì tốc độ
truy vấn dữ liệu bảng T2 tương đối nhanh
Dùng IN khi: Dữ liệu bảng T1 lớn hơn dữ liệu ở bảng T2
Dùng Exists khi: Dữ liệu bảng T2 lớn hơn dữ liệu bảng T1, trường điều kiện được đánh
index
Nếu dữ liệu cả 2 bảng đều lớn, hoặc tương đương nhau thì 2 cách dùng có thời gian thực
hiện tương đương nhau
2. Cấu trúc dữ liệu hình cây
Vấn đề: Bảng dữ liệu được thiết kế theo quan hệ cha – con, xây dựng cấu trúc hình cây dữ liệu,
lấy ra cấp của mỗi nút trên cây
Giải pháp: Sử dụng cấu trúc start with, connect by để lấy ra thông tin
Cấu trúc lệnh:
1
2
3
4
5
SELECT object_code, LPAD (' ', LEVEL * 5, ' ') || object_name,
CONNECT_BY_ROOT (object_code)
FROM objects
WHERE app_id = 2609
START WITH parent_id IS NULL
CONNECT BY PRIOR object_id = parent_id;
3. 6
Trong đó:
START WITH parent_id IS NULL: Điều kiện xác định nút gồc, có thể có nhiều nút gốc
trong trường hợp có nhiều cây
CONNECT BY PRIOR object_id = parent_id: hướng phát triển của cây, đây là cách xác
định nút con, vế có prior là nút cha đã được xác định, vế còn lại là nút con.
CONNECT_BY_ROOT(column_name) lấy ra giá trị trường của nút gốc
Level: Lấy ra cấp của nút, bắt đầu từ 1
Hàm LPAD(str1, length, str2): So sánh độ dài xâu str1 với length, nếu nhó hơn bao nhiêu
ký tự thì thêm bếnh nhiêu ký tự của xâu str2 vào bên trái xâu str1
3. Lấy ra n giá trị theo sắp xếp
Bài toán: Cho bảng SINHVIEN với 2 trường (MA_SV, DIEM), lấy ra 10 sinh viên có số điểm
cao nhất
Giải pháp:
– Cách 1: sử dụng thuộc tính rownum khi để giới hạn số lượng bản ghi lấy ra từ tập các bản ghi
đã sắp xếp tăng dần (hoặc giảm dầm).
Câu lệnh
1
2
3
4
5
SELECT *
FROM (SELECT *
FROM sinhvien
ORDER BY diem DESC)
WHERE ROWNUM <= 10
Nhận xét: Với cách sử dụng này ta lấy ra được đúng 10 bản ghi đứng đầu khi sắp xếp, trường
hợp có 20 sinh viên dẫn đầu có điểm bằng nhau thì chỉ lấy được 10 sinh viên
Lưu ý: Câu lệnh sau lấy ra 10 bản ghi nhưng không phải bản ghi có điểm lớn nhất, do thuộc tính
rownum được gán trước khi sắp xếp
1
2
3
4
SELECT *
FROM sinhvien
WHERE ROWNUM <= 10
ORDER BY diem DESC;
– Cách 2: Sử dụng hàm rank() over để đưa ra thứ tự của bản ghi
1
2
3
SELECT *
FROM (SELECT ma_sv, RANK () OVER (ORDER BY diem DESC) AS rank_diem
FROM sinhvien)
4. 4
5
WHERE rank_diem <= 10
ORDER BY rank_diem;
Nhận xét: Câu lệnh này lấy ra danh sách sinh viên thuộc top 10, có nghĩa là có thể có nhiều hơn
10 bản ghi nếu có nhiều sinh viên trùng điểm nhau. Điểm của sinh viên được sắp xếp là gán số
thứ tự, các sinh viên có điểm giống nhau thì có số thứ tự giống nhau.
Câu lệnh này lấy ra danh sách sinh viên thuộc top 10 điểm cao nhất (có thể >10 sinh viên)
4. Sử dụng Database Link
– Vấn đề: Để truy vấn dữ liệu từ một DB khác ta thông qua đối tượng Database link
– Câu lệnh tạo Database link:
1
2
3
4
5
6
7
8
9
10
11
12
CREATE SHARED DATABASE LINK dbl_test
CONNECT TO bccs_anypay_app IDENTIFIED BY abc
AUTHENTICATED BY bccs_anypay_app IDENTIFIED BY abc
USING '(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.58.3.65)(PORT = 1521))
)
(CONNECT_DATA =
(SID = dbtest)
)
)
';
– Câu lệnh sử dụng Database link:
1
2
SELECT *
FROM <schema_name>.<table_name>@dbl_test;
5. Sử dụng lệnh Merge
Vấn đề: Khi cần insert hoặc update dữ liệu từ bảng A sang bảng B có cấu trúc tương tự nhau mà
không cần kiểm tra bản ghi đó đã tồn tại hay chưa tao dùng câu lệnh sau:
1
2
3
4
5
6
7
8
MERGE INTO test1 a
USING test2 b
ON (a.object_id = b.object_id)
WHEN MATCHED THEN
UPDATE
SET a.status = b.status
WHEN NOT MATCHED THEN
INSERT (object_id, status)
VALUES (b.object_id, b.status)
5. 9
– Giải thích: Bảng test1, test2 có cấu trúc như nhau, câu lệnh trên dùng để đẩy dữ liệu từ bảng
test2 sang bảng test1, nếu bản ghi ở bảng test2 đã tồn tại ở test1 thì thực hiện update trường
status, ngược lại insert bản ghi mới vào bảng test1
6. Schema Trigger
– Vấn đề: Khi trong code có sử dụng các câu lệnh SQL thuần, tên bảng không đặt tên schema ở
đầu. Khi triển khai lên server, user dùng kết nối vào DB không phải là user chứa các bảng dữ
liệu
– Giải pháp: Tạm thời để chạy được các câu truy vấn với các bảng của một schema khác mà
không có tiền tố schema ở đầu ta tạo trigger set schema mặc định cho user sau khi đăng nhập =
schema chứa bảng dữ liệu
– Câu lệnh thực hiện:
1
2
3
4
5
6
CREATE OR REPLACE TRIGGER db_anypay_app_logon
AFTER LOGON ON DATABASE
WHEN (USER = 'BCCS_ANYPAY' )
BEGIN
execute immediate 'ALTER SESSION SET CURRENT_SCHEMA = ANYPAY_OWNER';
END;
7. Xóa dữ liệu trùng nhau
– Vấn đề: Khi bảng dữ liệu không có khóa chính có 2 hoặc nhiều bản ghi trùng nhau, nếu cần
xóa 1 bản ghi trong 2 hoặc nhiều bản ghi để tránh trùng lặp dữ liệu.
– Giái pháp: Để xóa 1 trong 2 bản ghi trùng nhau ta xác định các bản ghi bị lặp sau đó lấy ra 1
bản ghi dựa vào thuộc tính ROWID
– Câu lệnh thực hiện:
1
2
3
4
5
6
7
DELETE FROM users
WHERE ROWID IN (SELECT row_id
FROM (SELECT MAX (ROWID) AS row_id, COUNT (*),
user_id
FROM users
GROUP BY user_id
HAVING COUNT (*) > 1))
– Lưu ý: Nếu số bản ghi trùng nhau > 2 thì phải chạy nhiều lần để xóa hết
8. Thuộc tính rowdependencies của bảng
– Vấn đề: Với một bảng dữ liệu, khi cần biết thời gian sau cùng tác động lên bản ghi dữ liệu
– Giải pháp: Dựa vào thuộc tính ora_rowscn và sử dụng hàm scn_to_timestamp để chuyển về
6. kiểu date
– Ví dụ:
1
2
SELECT scn_to_timestamp (ORA_ROWSCN)
FROM staff;
– Để thông tin thuộc tính ora_rowscn với mỗi bản ghi khác nhau, khi tạo bảng ta phải đặt thuộc
tính rowdependencies cho bảng, ví dụ
1
2
3
4
5
6
7
CREATE TABLE tbl_temp
(
ID NUMBER(10),
user_name VARCHAR (20),
passwd VARCHAR (100)
)
ROWDEPENDENCIES;
9. Sử dụng select table as timestamp
– Vấn đề: Khi ta chẳng may xóa mất dữ liệu hoặc update 1 bản ghi và commit dữ liệu, ta cần
xem lại hoặc khôi phục lại bản ghi đó
– Giải pháp: Select bảng tại thời điểm trước khi xóa hoặc update dữ liệu bằng lệnh ten_bang as
of timestamp thoi_gian
– Câu lệnh:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-- xoa du lieu
DELETE FROM staff
WHERE staff_id = 172143;
-- commit du lieu
COMMIT ;
-- hien thi lai du lieu da xoa trong vong 1 ngay
SELECT *
FROM staff AS OF TIMESTAMP SYSDATE - 1
WHERE staff_id = 172143;
-- Khoi phuc lai du lieu da xoa
INSERT INTO staff
SELECT *
FROM staff AS OF TIMESTAMP SYSDATE - 1
WHERE staff_id = 172143;
-- commit du lieu
COMMIT;
7. 10. Thực hiện export database
– Điều kiện: Máy tính phải cài oracle_client, trong file ts_name phải có thông tin DB cần dump
Bước 1: gõ lệnh exp
Bước 2: nhập user_name/password@ts_name
Trong đó:
User_name: user đăng nhập DB
Password: mật khẩu đăng nhập
Ts_name: tên Database trong file ts_name
Bước 3: Nhập số byte buffer khi dump DB, nếu để mặc định là 4096 thì nhấn Enter
Bước 4: Nhập đường dẫn lưu file dmp trên máy local, sau khi dump sẽ sinh ra file duôi dmp và
lưu trên máy
Bước 5: Lựa chọn import cả schema hay chỉ một số bảng, nếu chọn export một số bảng thì phải
nhập lần lượt từng bảng
Bước 6: Lựa chọn có export dữ liệu trong bảng hay không, nếu chọn no thì chỉ export được cấu
trúc của bảng
Bước 7: Chọn nén dữ liệu khi export hay không? mặc định chọn yes
Bước 8: Nhập tên bảng cần export
Bước 9: Nhập tên bảng tiếp theo cần export
Bước 10: Nhấn Enter để bắt đầu quá trình export dữ liệu
11. Thực hiện import database
Bước 1: Gõ lệnh imp
Bước 2: Nhập thông tin kết nối vào Database
Bước 3: Nhập đường dẫn chứa file dump
Bước 4: Nhập số by dùng cho bộ nhớ đệm, thường để mặc định
Bước 5: Lựa chọn liệt kê nội dung của file import
Bước 6: Tùy chọn bỏ qua việc import nếu gặp lỗi tạo đối tượng đã có
Bước 7: Import quyền của các user đối với các đối tượng import
Bước 8: Tùy chọn import dữ liệu của bảng
Bước 9: Tùy chọn import toàn bộ file hay chỉ import theo schema
Bước 10: Nếu bước 9 chọn No thì phải nhập schema cần import
Bước 11: Tùy chọn import một số bảng hay là tất cả các bảng trong schema
12. Tìm kiếm bản ghi bị lock và kill session lock bản ghi
– Vấn đề: Khi thực hiện thao tác với dữ liệu của bảng, một số trường hợp bản ghi bị session lock
nhưng không có thao tác commit hay rollback nên không được giải phóng. Với các bản ghi này
người dùng không thể thực hiện update hay delete được
– Giải pháp: Tìm kiếm ra session đang lock bản ghi để thực hiện kill session đó
– Câu lệnh liệt kê ra các session lock đối tượng
8. 1
2
3
4
5
6
7
8
9
SELECT c.owner, c.object_name, c.object_type, b.SID, b.serial#, b.status,
b.osuser, b.machine,
'alter system kill session '''
|| b.SID
|| ','
|| b.serial#
|| ''' IMMEDIATE;' AS kill_sta
FROM v$locked_object a, v$session b, dba_objects c
WHERE b.SID = a.session_id AND a.object_id = c.object_id;
– Câu lệnh kill session
1ALTER SYSTEM KILL SESSION 'sid,serial#';
Trong đó: SID, Serial#: được lấy từ bảng v$session
13. Một số bảng hệ thống hay sử dụng
– Bảng v$sql: Lưu các câu lệnh tác động vào Database
– Bảng v$session: Lưu các session hiện tại đang kết nối vào DB
– Bảng v$locked_object: Lưu các đối được đang bị lock do một số thao tác cập nhật cấu trúc, dữ
liệu
– V$SPPARAMETER: Bảng lưu tham số cấu hình của hệ thống
14. Toán tử: some, any, all
– Toán tử all: Được sử dụng để so sánh giá trị của một trường với một danh sách giá trị, toán tử
all đi sau =, !=, >, <, <=, >=.
– Bài toán: Cho bảng sinh_vien với các trường ma_sv, lop, diem. Tìm tất cả các sinh viên của
lớp A có điểm lớn hơn bất kỳ sinh viên nào của lớp B
– Câu lệnh như sau:
1
2
3
4
5
SELECT *
FROM sinh_vien
WHERE lop = 'A' AND diem > ALL (SELECT diem
FROM sinh_vien
WHERE lop = 'B');
– Giải thích: khi dùng toán tử all thì giá trị của cột diem phải > bất kỳ giá trị nào trong tập được
chỉ ra sau all
– Toán tử any, some: trong oracle 2 toán tử này có ý nghĩa như nhau:
Bài toán: với bảng sinh_vien như trên, lấy ra danh sách các sinh viên lớp A có điểm lớn hơn 1
trong các sinh viên của lớp B
– Câu lệnh:
9. 1
2
3
4
5
6
7
8
9
10
SELECT *
FROM sinh_vien
WHERE lop = 'A' AND diem > ANY (SELECT diem
FROM sinh_vien
WHERE lop = 'B');
SELECT *
FROM sinh_vien
WHERE lop = 'A' AND diem > SOME (SELECT diem
FROM sinh_vien
WHERE lop = 'B');
15. Sử dụng bảng tạm để lưu trữ dữ liệu (TEMPORARY
TABLE)
– Vấn đề: Trong một số trường hợp cần tổng hợp dữ liệu để xuất báo cáo hoặc đưa dữ liệu hiển
thị ra giao diện. Khi ta không thể dùng 1 câu lệnh để lấy ra dữ liệu mà tổng hợp qua nhiều bước
thì ta cần lưu lại dữ liệu tổng hợp sau đó lấy dữ liệu
– Giải pháp: Trong oracle hỗ trợ việc tạo một bảng tạm (temporary table) để lưu trữ dữ liệu tạm
thời với các đặc điểm:
Thao tác: Có thể sử dụng các câu Query, DML để thao tác với Temporary Table giống
như một table bình thường.
Lưu trữ: Temporary table sử dụng Temporary tablespace để lưu dữ liệu.
Ảnh hưởng: Dữ liệu chỉ có hiệu lực trong phạm vi một Session hoặc một Transaction,
việc quy định bảng nằm trong câu lệnh tạo bảng:
1
2
3
4
5
6
7
8
9
10
11
-- Du lieu chi ton tai trong 1 transation
CREATE GLOBAL TEMPORARY TABLE my_temp_table (
column1 NUMBER,
column2 NUMBER
) ON COMMIT DELETE ROWS;
--du lieu ton tai trong session
CREATE GLOBAL TEMPORARY TABLE my_temp_table (
column1 NUMBER,
column2 NUMBER
) ON COMMIT PRESERVE ROWS;
Bảo mật: Cho dù dữ liệu đã commit, mỗi session cũng chỉ thấy được dữ liệu trong session
đó
Xung đột: Do mỗi session có phần dữ liệu riêng nên tránh được việc xung đột dữ liệu, ví
dụ như việc ghi đè dữ liệu của nhau là không xảy ra.
Dọn rác: Temporary table tự động dọn sạch dữ liệu khi kết thúc Session hoặc
Transaction.
10. – Ngoài ra còn có một số đặc điểm khác như:
Có thể tạo trigger, index trên temporary table.
Khi dùng lệnh truncate (DDL), chỉ có dữ liệu trên session hiện tại bị mất.
Khi export, phần cấu trúc của Temporary table cũng được export theo như table thường.
16. Dùng ký tự loại trừ trong Oracle với toán tử like
– Vấn đề: Khi sử dụng toán tử like để tìm kiếm xâu gần đúng ta thường dùng 2 ký tự thay thế là
‘%’(thay thế cho 1 chuối) và ‘_’ (thay thế cho 1 ký tự). Trường hợp ta muốn tìm kiếm theo các
trường có chứa ký tự này ta phải dùng ký tự loại trừ
– Giải quyết: Trong Oracle để dùng ký tự loại trừ sau toán tử like ta dùng toán tử escape, cú pháp
như sau:
1select * from test1 where col1 like '%_' escape '';
– Trong đó: ‘’ là ký tự loại trừ, ta có thể thay thế ký tự ‘’ bằng 1 ký tự bất kỳ ngoài ‘%’, ‘_’.
Khi sử dụng ký tự loại trừ ta làm mất ý nghĩa của ký tự thay thế đứng ngay sau nó, nó trở thành 1
ký tự thường
17. Đánh partition tự động
– Vấn đề: Đối với các bảng dữ liệu có đánh partition theo tháng hoặc theo ngày, người QTHT
thường xuyên phải đánh partition, nếu quên dữ liệu insert vào sẽ bị lỗi và có thể dẫn đến lỗi toàn
hệ thống.
– Giải pháp: Để giải quyết vấn đề trên ta thường viết thủ tục đánh partition tự động cho bảng và
đặt scheduler để chạy định kỳ. Việc đánh partition không ảnh hưởng tới các thao tác insert,
select, update, delete.
– Tư tưởng: Để đảm bảo có thể đánh partition một cách tự động ta phải đặt tên partition theo một
số quy ước:
Trong tên partition phải chứa thông tin về ngày tháng của dữ liệu
Phần đầu của tên partition phải giống nhau
– Dựa vào thông tin partition trong tên ta xác định thời gian cần đánh partition tiếp theo
Code:
1
2
3
4
5
6
7
8
9
PROCEDURE proc_create_partition
IS
CURSOR c_partition
IS
SELECT object_name,
MAX (SUBSTR (subobject_name,
LENGTH (subobject_name) - 5,
LENGTH (subobject_name)
)
) AS sub_partition
FROM user_objects
11. 10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
WHERE object_type = 'TABLE PARTITION'
AND object_name NOT LIKE 'BIN$%'
AND object_name NOT IN ('AGENT_COUNTER')
GROUP BY object_name;
v_loop_str VARCHAR (3000);
v_date DATE;
p_error VARCHAR (2000);
BEGIN
FOR v_partition IN c_partition
LOOP
v_date := TO_DATE (v_partition.sub_partition, 'yyMMdd');
WHILE v_date <=
ADD_MONTHS (TO_DATE (v_partition.sub_partition, 'yyMMdd'),
1)
LOOP
BEGIN
v_date := v_date + 1;
v_loop_str := '';
v_loop_str :=
'alter table '
|| v_partition.object_name
|| ' add partition DATA20'
|| TO_CHAR (v_date, 'yyMMdd')
|| ' values less than (to_date(''20'
|| TO_CHAR (v_date, 'yyMMdd')
|| ''',''yyyyMMdd''))';
DBMS_OUTPUT.put_line (v_loop_str);
EXECUTE IMMEDIATE v_loop_str;
v_loop_str := '';
EXCEPTION
WHEN OTHERS
THEN
p_error := 'Loi xay ra khi them partition: ' || SQLERRM;
DBMS_OUTPUT.put_line (p_error);
END;
END LOOP;
END LOOP;
END;
18. Drop scheduler đang chạy
12. 1
2
3
4
5
BEGIN
DBMS_SCHEDULER.drop_job (job_name => 'TTPM_DBA.SESSION_VIEW_JOB',
FORCE => TRUE
);
END;
19. Mã hóa thủ tục, function trong database
– Vấn đề: Với một số thủ tục, funcion cần bảo mật thông tin. Sau khi tạo ta cần mã hóa nội dung
để người khác không xem được
– Giải pháp: Sử dụng hàm mã hóa của oracle theo cú pháp
1
2
3
BEGIN
SYS.DBMS_DDL.create_wrapped (str);
END;
– Trong đó: str là xâu chứa câu lệnh tạo thủ tục
20. Commit trong hàm khi viết package
– Vấn đề: Trong một số trường hợp khi thực hiện thao tác cập nhật dữ liệu trong một hàm ta cần
commit hoặc rollback dữ liệu nhưng không muốn làm ảnh hưởng đến các phần khác. Ví dụ đối
với hàm ghi log
– Giải pháp: Giới hạn phạm vi commit, rollback dữ liệu trong hàm bằng cú pháp PRAGMA
AUTONOMOUS_TRANSACTION
– Ví dụ:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
PROCEDURE insert_rp_log_error (
p_app VARCHAR2,
p_type VARCHAR2,
p_object VARCHAR2,
p_sta_datetime DATE,
p_end_datetime DATE,
p_description VARCHAR2
)
IS
PRAGMA AUTONOMOUS_TRANSACTION;
v_error VARCHAR2 (4000);
BEGIN
INSERT INTO cm_pos2.rp_log_error
(app, TYPE, table_name, sta_datetime, end_datetime,
description
)
VALUES (p_app, p_type, p_object, p_sta_datetime, p_end_datetime,
p_description
);
COMMIT;
EXCEPTION