Showing posts with label Database. Show all posts
Showing posts with label Database. Show all posts

Tuesday, May 10, 2011

Oracle – Important Queries

– List of tables in DB
SELECT * FROM TABS
SELECT * FROM USER_TABLES
SELECT * FROM user_all_tables;
SELECT * FROM USER_objects where object_type = ‘TABLE’;
SELECT * FROM ALL_ALL_TABLES;
SELECT * FROM DBA_TABLES; — Need Privileges to run this
SELECT * FROM DICT;
SELECT * FROM DICTIONARY;
– List of table spaces
SELECT * FROM USER_TABLESPACES
– List of previlages on tabel
SELECT * FROM TABLE_PRIVILEGES;
SELECT * FROM table_privilege_map;
– List of constraints
SELECT * FROM user_constraints;
– Get Primary key
SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner
FROM all_constraints cons, all_cons_columns cols
WHERE cols.table_name = ‘TABLE_NAME’
AND cons.constraint_type = ‘P’
AND cons.constraint_name = cols.constraint_name
AND cons.owner = cols.owner
ORDER BY cols.table_name, cols.position;
– Get Schema names
SELECT * FROM ALL_USERS
– Get segment assigned
– All table columns
SELECT * FROM ALL_TAB_COLS

Oracle – Wildcards

Demo Table And Records
Demo Data CREATE TABLE wildcard (
test VARCHAR2(25)); INSERT INTO wildcard VALUES (’23%45′);
INSERT INTO wildcard VALUES (’2345′);
INSERT INTO wildcard VALUES (’2365′);
INSERT INTO wildcard VALUES (‘Daniel Morgan’);
INSERT INTO wildcard VALUES (‘Washington’);
COMMIT;

Wildcard Characters
Single Character _ (underscore)
SELECT *
FROM wildcard
WHERE test LIKE ’23_5′;
Multiple Characters
SELECT *
FROM wildcard
WHERE test LIKE ’2%5′;
Mixed Single And Multiple Characters SELECT *
FROM wildcard
WHERE test LIKE ‘_3%5′;
Complex Statement SELECT *
FROM wildcard
WHERE test LIKE ‘%a%a %‘;

Querying Records Containing Wildcards
Find Records Containing Percentage Sign ESCAPE ‘<escape_character>’
SELECT *
FROM wildcard
WHERE test LIKE ‘%\%%ESCAPE ‘\’;

INSTEAD-OF trigger

A trigger is a database object similar to a stored procedure that executes in response to certain actions that occur in your database environment. SQL Server 2005 is packaged with three flavors of trigger objects: AFTER, data definition language (DDL), and INSTEAD-OF.
AFTER triggers are stored procedures that occur after a data manipulation statement has occurred in the database, such as a delete statement. DDL triggers are new to SQL Server 2005, and allow you to respond to object definition level events that occur in the database engine, such as a DROP TABLE statement. INSTEAD-OF triggers are objects that will execute instead of data manipulation statements in the database engine. For example, attaching an INSTEAD-OF INSERT trigger to a table will tell the database engine to execute that trigger instead of executing the statement that would insert values into that table.

Why use an INSTEAD-OF trigger?

INSTEAD-OF triggers are very powerful objects in SQL Server. They allow the developer to divert the database engine to do something different than what the user is trying to do. An example of this would be to add an INSTEAD-OF trigger to any table in your database that rolls back transactions on tables that you do not want modified. You must be careful when using this method because the INSTEAD-OF trigger will need to be disabled before any specified modifications can occur to this table.
Perhaps a more functional reason to use an INSTEAD-OF trigger would be to add the trigger to a view. Adding an INSTEAD-OF trigger to a view essentially allows you to create updateable views. Updateable views allow you to totally abstract your database schema so you can potentially design a system in such a way that your database developers do not have to worry about the OLTP database schema and instead rely upon a standard set of views for data modifications.

An example

To better illustrate the idea of an updateable view, it’s always great to use an example. In this example, I refer to a fictitious scenario that includes a Products lookup table and a Purchases table, which records those instances where products are purchased. Shown below Listing A contains the script to create these tables. After running the script to create the tables I will use in the example, I will run the script in Listing B to insert some data into the tables.
Now that the sample tables have data in them, I can create a view to join these tables and present the data in a meaningful way. Check out Listing C.
This is a pretty typical production-level view. It joins two tables in the database structure, which greatly simplifies data retrieval. However, the data abstraction provided is not the only advantage of using views. Attaching INSTEAD-OF trigger(s) to this view allows me to modify the underlying tables, so that I may never need to modify the data in the underlying tables directly. I’ll use the script in Listing D to create an INSTEAD-OF trigger on the vw_ProductPurchases view.
Notice that in the trigger declaration I specify the INSTEAD OF clause. Triggers created in SQL Server are AFTER triggers by default, so I must specify the INSTEAD OF clause in the trigger definition.
The first statement in the trigger is a “check” statement. Here I am checking the INSERTED table to ensure that the ProductID is present, and that either the PurchasePrice or the ProductPrice has been provided.
If the necessary data has been inserted into the view via an INSERT statement, the trigger will insert the specified values into the underlying data table. This is what a sample INSERT statement into the view would look like.
INSERT INTO vw_ProductPurchases(ProductID, PurchasePrice) VALUES(1, 700)
This INSERT statement provides a valid ProductID and PurchasePrice, which means a new record will be inserted into the Purchases table.

Conclusion

With a bit of imagination, it is easy to see the power and flexibility provided by INSTEAD-OF triggers. If your system is not extremely large, using a system of views to abstract your underlying database schema can provide a great way to shield your database programmers from modifying the data in the underlying tables directly.
Listing A:
CREATE TABLE Products
(
ProductID SMALLINT IDENTITY(1,1) PRIMARY KEY,
Description VARCHAR(75),
Price MONEY NOT NULL
)
GO
CREATE TABLE Purchases
(
PurchaseID SMALLINT IDENTITY(1,1) PRIMARY KEY,
ProductID SMALLINT REFERENCES Products(ProductID),
PurchasePrice MONEY NOT NULL,
PurchaseDate SMALLDATETIME DEFAULT(GETDATE())
)
Listing B:
INSERT INTO Products(Description, Price) VALUES('Television',500)

INSERT INTO Products(Description, Price) VALUES('VCR',100)

INSERT INTO Products(Description, Price) VALUES('DVD_Player',125)

INSERT INTO Products(Description, Price) VALUES('Alarm_Clock',40)

INSERT INTO Products(Description, Price) VALUES('Camera',325)

INSERT INTO Products(Description, Price) VALUES('Projector',1500)

INSERT INTO Products(Description, Price) VALUES('XBox',400)

GO

INSERT INTO Purchases(ProductID, PurchasePrice) VALUES(1, 500)

INSERT INTO Purchases(ProductID, PurchasePrice) VALUES(5, 325)

INSERT INTO Purchases(ProductID, PurchasePrice) VALUES(1, 525)

GO

Listing C:
CREATE VIEW vw_ProductPurchases

AS
      SELECT
            pr.ProductID,
            pr.Description,
            pr.Price AS ProductPrice,
            pu.PurchasePrice,
            pu.PurchaseDate  
      FROM
            Products pr
            INNER JOIN Purchases pu ON pr.ProductID = pu.ProductID

GO
Listing D:
CREATE TRIGGER tr_vwProductPurchases ON vw_ProductPurchases

INSTEAD OF INSERT

AS

BEGIN
      IF EXISTS
      (
            SELECT TOP 1 *
            FROM INSERTED
            WHERE
                  ProductID IS NOT NULL AND
                  ISNULL(COALESCE(PurchasePrice, ProductPrice),0)>0
      )
      BEGIN
            INSERT INTO Purchases
            (
                  ProductID, PurchasePrice, PurchaseDate
            )
            SELECT

i.ProductID, COALESCE(PurchasePrice, ProductPrice), ISNULL(PurchaseDate, GETDATE())
            FROM INSERTED i  
      END
      ELSE
      BEGIN
            PRINT 'Adequate data not provided.'
      END

END

Oracle – Connect By Prior

– Populate data
set feedback off
create table test_connect_by (
parent     number,
child      number,
constraint uq_tcb unique (child)
);
insert into test_connect_by values ( 5, 2);
insert into test_connect_by values ( 5, 3);
insert into test_connect_by values (18,11);
insert into test_connect_by values (18, 7);
insert into test_connect_by values (17, 9);
insert into test_connect_by values (17, 8);
insert into test_connect_by values (26,13);
insert into test_connect_by values (26, 1);
insert into test_connect_by values (26,12);
insert into test_connect_by values (15,10);
insert into test_connect_by values (15, 5);
insert into test_connect_by values (38,15);
insert into test_connect_by values (38,17);
insert into test_connect_by values (38, 6);
insert into test_connect_by values (null, 38);
insert into test_connect_by values (null, 26);
insert into test_connect_by values (null, 18);
– Main Query
SELECT LPAD(‘ ‘,2*(level-1)) || TO_CHAR(child) s
FROM test_connect_by
START WITH parent IS NULL
CONNECT BY PRIOR child = parent;

Database – Common Key Terminology

  • Key. A key is one or more data attributes that uniquely identify an entity.  In a physical database a key would be formed of one or more table columns whose value(s) uniquely identifies a row within a relational table.
  • Composite key.  A key that is composed of two or more attributes.
  • Natural key.  A key that is formed of attributes that already exist in the real world.  For example, U.S. citizens are issued a Social Security Number (SSN)  that is unique to them (this isn’t guaranteed to be true, but it’s pretty darn close in practice).  SSN could be used as a natural key, assuming privacy laws allow it, for a Person entity (assuming the scope of your organization is limited to the U.S.).
  • Surrogate key.  A key with no business meaning.
  • Candidate key.  An entity type in a logical data model will have zero or more candidate keys, also referred to simply as unique identifiers (note: some people don’t believe in identifying candidate keys in LDMs, so there’s no hard and fast rules).  For example, if we only interact with American citizens then SSN is one candidate key for the Person entity type and the combination of name and phone number (assuming the combination is unique) is potentially a second candidate key.  Both of these keys are called candidate keys because they are candidates to be chosen as the primary key, an alternate key  or perhaps not even a key at all within a physical data model.
  • Primary key.  The preferred key for an entity type.
  • Alternate key. Also known as a secondary key, is another unique identifier of a row within a table.
  • Foreign key. One or more attributes in an entity type that represents a key, either primary or secondary, in another entity type.

SQL Server – Best practices (index optimization,Database Performance)

Do you have a maintenance window to perform database reindexing?
Have you ever performed full set of re-organize and re-index process on a bigger database?
Do you know there are best practices to deploy in this regard?
On large database systems, with large numbers of insert and update commands, the problem of index fragmentation is one of the main causes of performance degradation and a proper index optimization strategy is a must.
Also following are set of counters you need to keep in mind:
· Create Index on frequently used columns in T-SQL Code. Columns used in WHERE, ORDER BY and GROUP BY are good candidate for Indexes. Create Index on column which are used in JOIN Condition.
· Remove any un-necessary Indexes. As Index occupies hard drive space as well as it decreases performance of all the insert, updates, deletes to the table.
· Smaller Index Key gives better performance than Index key which covers large data or many columns
· Multiple Columns Index or Covered Index should be ordered as Most Selective column on left and gradually decreasing selectivity as they go right.
· Use SORT_IN_TEMPDB option when table is created if tempdb is on different disk. This will increase the performance to create Index.
Also there are few basic guidelines when you need to create a database from scratch such as,
· Design a normalized database.
· Optimize a database design by denormalizing.
· Optimize data storage.
· Manage concurrency – by selecting the appropriate transaction isolation level.
· Select a locking granularity level.
· Optimize and tune queries for performance.
· Optimize an indexing strategy.
· Decide when cursors are appropriate.
· Identify and resolve performance-limiting problems.
· Be familiar with index structures and index utilization. Specifically, they must understand the interaction between non-clustered indexes, clustered indexes and heaps. A must know why a covering index can improve performance.
· Be able to design a database to third normal form (3NF) and know the trade offs when backing out of the fully normalized design (denormalization) and designing for performance and business requirements in addition to being familiar with design models, such as Star and Snowflake schemas.

SQL Server-Find nth highest salary

First Method:
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
Second Method:
Select * from ( select rank() over (partition by sal order by sal desc NULLS LAST) rn from tablename)
where rn = &N;
Third Method:
Find 1, 2,3 and nth highest salary
select top 1 salary from (
select distinct top n salary from tab order by salary desc ) a
order by salary asc
Fourth Method(Oracle):
select level, max(‘col_name’) from my_table
where level = ‘&n’
connect by prior (‘col_name’) > ‘col_name’)
group by level;

SQL Server – How to remove duplicate rows

IF OBJECT_ID(‘EmployeeDetails’) IS NOT NULL
DROP TABLE EmployeeDetails
CREATE TABLE [dbo].[EmployeeDetails]
(
[Employee] [varchar](10) NULL,
[JoiningDate] [datetime] NULL,
[DeptID] [int] NULL
)
GO
INSERT INTO EmployeeDetails(Employee, JoiningDate, DeptID)
SELECT ‘Gorav’,’1919-03-18 ‘,1008
UNION ALL
SELECT ‘Maneesh’,’1927-03-18 ‘,91
UNION ALL
SELECT ‘Anant’,’1927-04-01 ‘,139
UNION ALL
SELECT ‘Gorav’,’1919-03-18 ‘,1008
UNION ALL
SELECT ‘Maneesh’,’1927-03-25 ‘,92
UNION ALL
SELECT ‘Anant’,’1927-03-25 ‘,108
UNION ALL
SELECT ‘Gorav’,’1919-04-01 ‘,150
UNION ALL
SELECT ‘Maneesh’,’1927-04-01 ‘, 123
UNION ALL
SELECT ‘Anant’,’1927-04-01 ‘, 139
UNION ALL
SELECT ‘Gorav’,’1919-04-08 ‘, 168
– query to check duplicate rows
SELECT Employee, JoiningDate, DeptID,Ranking = row_number() OVER(PARTITION BY Employee, JoiningDate, DeptID ORDER BY NEWID() ASC)
FROM EmployeeDetails
– query to delete duplicate rows
WITH RemoveDuplicate(Employee, JoiningDate, DeptID, Ranking)
AS(
SELECT Employee, JoiningDate, DeptID,Ranking = row_number() OVER(PARTITION BY Employee, JoiningDate, DeptID ORDER BY NEWID() ASC)
FROM EmployeeDetails
)
DELETE FROM RemoveDuplicate WHERE Ranking > 1

Database best practices

1. Store relevant and necessary information in the database instead of application structure or array.
2. Use normalized tables in the database. Small multiple tables are usually better than one large table.
3. If you use any enumerated field create look up for it in the database itself to maintain database integrity.
4. Keep primary key of lesser chars or integer. It is easier to process small width keys.
5. Store image paths or URLs in database instead of images. It has less overhead.
6. Use proper database types for the fields. If StartDate is database filed use datetime as datatypes instead of VARCHAR(20).
7. Specify column names instead of using * in SELECT statement.
8. Use LIKE clause properly. If you are looking for exact match use “=” instead.
9. Write SQL keyword in capital letters for readability purpose.
10. Using JOIN is better for performance then using sub queries or nested queries.
11. Use stored procedures. They are faster and help in maintainability as well security of the database.
12. Use comments for readability as well guidelines for next developer who comes to modify the same code. Proper documentation of application will also aid help too.
13. Proper indexing will improve the speed of operations in the database.
14. Make sure to test it any of the database programming as well administrative changes.
15. SELECT count(1) from Table1 will be faster then SELECT count(*) from table1

Same SQL Query in 4 different ways

1. With Sub Query
SELECT Name, Region FROM bbc
WHERE Region In(
SELECT Region FROM bbc WHERE Name=’India’ OR Name=’Iran’)
2. With Exists clause
SELECT Name, Region FROM bbc b
WHERE EXISTS(SELECT Region FROM bbc WHERE Region = b.Region
AND (Name=’India’ OR Name=’Iran’))
3. With Old style joins
SELECT b.Name, b.Region FROM bbc b, bbc c
WHERE b.Region = c.Region
AND ((c.Name=’India’) OR (c.Name=’Iran’))
4. With ANSI Joins
SELECT b.Name, b.Region FROM bbc b
INNER JOIN bbc c
ON b.Region = c.Region
AND ((c.Name=’India’) OR (c.Name=’Iran’))