DATA MODELING FAQS

 Difference between Row_number(), Rank() and Dense_rank() is 


In case of value is same then 
Row_number()  gives : sequential number 
Rank  () : Assigns same Rank but the (next rank )= (total previous ranks +1 )
Dense_Rank() : Assigns same rank and next rank = next sequential number 

=========================================
a) Rownum :

( To find 2nd highest salary using ROW_NUMBER)

select empid,salary from (

select e.*,row_number() over (order by salary desc)

as row_num from emp e )

where row_num = 3 ;


======================
b) using Rank :
 

-- To show only 2nd highest --

select * from

(select e.*,rank() over (order by salary desc) as rank

from emp e )

where rank = 2;


-- ** To display ranks ** --

select rank() over (order by salary desc) as rank,e.*

from emp e ;


======================


c ) Dense Rank ( BEST )

-- To show only 2nd highest --

select * from

(select e.*,dense_rank() over (order by salary desc) as rank

from emp e )

where rank = 2;


-- ** To display ranks ** --

select dense_rank() over (order by salary desc) as rank,e.*

from emp e ;


======================

d) using count distinct
select empno ,sal from emp e1
where 3 =
(select count(distinct sal )
from emp e2
where e2.sal > e1.sal )


====================================================

 Common mistakes of Data modeling :  

  • neglecting stakeholder input,

  •  inconsistent naming conventions,

  • and failing to adequately test and

  •  validate the model. 

  • not considering data quality,

  •  ignoring business requirements,
  •  and overlooking future scalability needs. 

=====================================================
VARCHAR AND NVARCHAR

VARCHAR uses single-byte character sets (like ASCII), 

while NVARCHAR 

uses Unicode, allowing for a wider range of characters including those from multiple languages. NVARCHAR typically requires more storage space and has a shorter maximum character length compared to VARCHAR


====================================================

 Erwin - Forward and reverse engineering steps Forward engr steps :
Actions > schema > Generate scripts

Reverse engnr steps :
Actions > reverse engnr > logical / physical >
Database (or) script file > connect > ok
 
16 Erwin - Complete compare feature Complete Compare is a powerful tool that lets you view and resolve the differences between two models, or a model and a database or script file

Actions > complete compare wizared > source target models
select > compare > final > resolve differenceces

17 Erwin - Naming standards Use the Naming Standard Editor to create naming standards and develop a glossary that contains glossary words, their abbreviations, and alternate abbreviations.

Access the Model Explore> open Naming Standard Editor > Define naming standards for logical and physical models> Create abbreviations

========================================================


ODS is a temportary data store from all sources for volatile data like resumes of interview, quotation from suppliers ,etc. which need not be stored permanently

========================================================

Possible Reasons for Slow SQL Queries

  1. Lack of Indexes: I 
  2. Complex Joins
  3. Large Data Volume:  
  4. Inefficient Query Structure
  5. Database Configuration: Configuration settings such as memory allocation, cache size, and connection limits can affect performance.
  6. Server Load: High server load due to concurrent queries or insufficient resources (CPU, memory, I/O) can slow down execution times.
  7. Network Latency: If the database is remote, network latency can add to the time it takes to execute a query.
  8. Statistics Outdated: Database optimizers rely on statistics to create execution plans.  
  9. Locking and Blocking: If a query is waiting for locks held by other transactions, it can slow down execution.
========================================================
Data quality checks -pg 28

1. CONSISTENCY
2. ACCURACY
3. COMPLETENESS
4. AUDITABLITY
5. ORDERLINESS
6. UNIQUENESS
7. TIMELINESS

========================================================

44 Types of indexes 

1. NORMAL INDEX
2. BITMAP INDEX
3. UNIQUE & NON UNIQUE INDEX
4. CLUSTERED & NON CLUSTERED
5. PARTITIONED & NON PARTITIONED
6. EXPRESSION BASED
7. B- TREE

========================================================
Normalization (34)

1NF - There should not be multiple values in each cell
2NF- in 1NF and  All non Non key attributes should be dependent on key attributes and all.
3NF  -  It should be in 2NF  - And  there should not be any transitive dependency
4NF : Avoids multivalued dependency like 
    Student id , courses , subjects are not related , multivalued and in same table

========================================================

Sql query : find and delete duplicate rows Two methods to find and delete duplicate rows
 
Method 1. using id Column (if ID column is unique, but title is duplicate)

Delete all rows other than min id value ..(used when id column is not duplicate but other columns values are duplicate) 

================================
delete films
where film_id 
not in (select min(film_id) from films group by title, rel_date)
 
Method 2. using CTE ( Two steps)
============================================
step 1 :

with CTE as
(select id ,name , email , row_number()
over (partition by name , email order by name , email ) rownum
from sales

step 2 :
Delete from CTE where rownum > 1
===========================================
Method 3. using ROWID
============================================
Delect from table1
where rowid not in (select min(rowid) from table 1
group by col1,col2)


========================================================

  what is inner join and outer join count of below

A       B

1       1

1       1

2       2

3

null   null Inner join = count of matching rows

outer join = inner join + left side unmatched


inner = 6 rows

left outer = 6 + 1 = 7 rows 

 ========================================================

Which tools used for 'schema comparision''
1) SQL Server Data Tools (SSDT)

2) SQLDBDiff. : SQLDBDiff is a powerful and intuitive tool that compares the

 ========================================================

What are ACID properties
Atomicity - each statement in a transaction Either the entire statement is executed, or none of it is executed.

Consistency - This means that integrity constraints must be maintained so that the database is consistent before and after the transaction

Isolation -Changes occurring in a particular transaction will not be visible to any other transaction until that transaction has been committed

Durability - once the transaction has completed execution, the updates and modifications to the database are stored in and written to disk and are permanent

 ========================================================
56 How to do Data model testing
Data model can tested using the following:
Unit testing: This involves testing each component of the data model individually to ensure that it performs as expected.
Integration testing: This involves testing how different components of the data model work together
using test data
 ========================================================
51 What are roles of data modeler 61

  • get the data from data source
  • identify connect the data source
  • pick a share data set
  • select storage mode identify the query performance issues
  • use or create a data flow

  • profile the data
  • identify data anomalies
  • examine data structures

  • clean transform load data
  • resolve inconsistencies and unexpected values null values data quality issues
  • apply value replacements identify the keys for joints
  • identify and transform column data types
  • apply naming conventions two columns
  • perform data loading
  • resolve data input errors

  • model the data
  • designer data model
  • define the tables
  • configure table and column properties
  • flatten the parent child hierarchy
  • role playing dimensions
  • define relationships and cardinality
  • design the data model
  • resolve many to many relationships
  • design a common date table
  • define the data level granularity

========================================================
 what are layers in Datalake

 1. landing layer
2. curated layer
3. application data layer ( summary data)
4. Sand box layer
5. Target layer
========================================================

steps to prepare STTM
Steps Involved in Source to Target Mapping
You can map your data from a source of your choice to your desired destination by implementing the following steps:
Step 1: Defining the Attributes 
Step 2: Mapping the Attributes 
Step 3: Transforming the Data
 Step 4: Give Standard Naming Conventions Specifics 
Step 5: Establish Flows for Data Mapping
Step 6: Establish Data Transformation Guidelines 
Step 7: Testing the Mapping Process 
Step 8: Deploying the Mapping Process 
Step 9: Maintaining the Mapping Process  

========================================================
Diff. View and materialized view

Views and materialized views are both database objects that provide access to data, but they differ in several ways: 

Storage
Views are virtual and don't store data
, while materialized views store precomputed data as a physical table. 
Performance
Views are more efficient because they don't require storage or updates,
but materialized views can be faster for complex queries and aggregations. 

========================================================

What is data lienage  

is a process of documentation of  ETL all steps through which each table and each column has gone thru till final target in a diagram 
its like building a data model ( add entities attributes )
here we (add tables columns and next stage in diagrams )

========================================================

What is Data governance

  • Data governance is 
    • a set of processes, policies, roles, metrics, and standards  
    • that help  management processes to keep 
      data secure, private, accurate, and usable throughout its life cycle. 

========================================================
What is a Data Lake?

A data lake is a centralized repository that allows you to store all your structured and unstructured data at any scale. You can store your data as-is,
 
A data lakehouse
 
is a data architecture that combines a data lake and a data warehouse to provide a flexible solution for business intelligence and data science. It allows organizations to use low-cost, flexible storage for all types of data, while also benefiting from the data management, schema, and governance of a warehouse.


Data warehouses
Store structured data from multiple sources. They are good for business intelligence (BI), data visualizations, reporting, and accessing reliable, quality data. Data warehouses are designed for the fastest query performance, and are optimized to analyze relational data coming from transactional systems and line of business application

========================================================

SQL : query to show Total salary  of each department

 ===========================

SELECT

  Id,   empname,   deptid,   Salary,

  SUM(Salary) OVER(PARTITION BY deptid) AS SUM_SAL

FROM

  emp  ORDER BY    id

 ===========================

# Id, empname, deptid, Salary, SUM_SAL

'1', 'john', '1', '20000', '50000'

'2', 'kem', '1', '30000', '50000'

'3', 'chan', '2', '10000', '30000'

'4', 'henry', '2', '20000', '30000'



========================================================

 SQL : query to sum of salary by dept and 
cumulative salary by each dept 

 SELECT  deptid,salary ,  

       Sum(salary)

         OVER(

           partition BY deptid

           ORDER BY id) AS CUMulative_SAL

FROM   emp

ORDER  BY id 

===============================

# deptid, salary, CUMulative_SAL

'1', '20000', '20000'

'1', '30000', '50000'

'2', '10000', '10000'

========================================================


 68. When to use star schema and when to go for snowflake ?

 If you have a few dimensions   and low cardinality (less unique values in dims ) , but you require fast query execution, a star schema is the right choice. 

 However, if you have several dimensions and high cardinality, a snowflake schema will be a better scheme 


Create a Delta Version

You create a delta version when you save a model initially or when you incrementally save an existing model.

Follow these steps:

  1. Click File, MartOpen >
    > The Open Model dialog opens. > Select a model and click OK.
    > The model opens.
    >Make necessary changes to the model.
    >Click File, Mart, Save.

  2. A delta version of the model is created with the incremental changes.

=========================================================================Create a Named Version

A named version of a model represents a milestone in the development of the model. You create a named version to keep that model version indefinitely.

Follow these steps:

  1. Click File, Mart, Catalog Manager   .

    > The Catalog Manager opens. > Select a model version,
    >right-click and click Mark Version. 

  2. A named version is created with a default name.
    > Edit the name of the named version (new name ) and press enter.

  3. A new named version is created in the catalog.


========================================================

When to use a surrogate key
if you want to allow duplicates to view the history of changes ( scd) then you can add a surrogate key (sequential number column) so that you can pick the highest values from duplicates as the latest entry 

==========================================================


where do we use data vault modeling

A data vault is a data modeling approach and methodology used in enterprise data warehousing to handle complex and varying data structures. It combines the strengths of 3rd normal form and star schema.
===============================================================
EDW and DW diff

Key Similarities
  • Centralized Data Repository: 
    Both are central locations for storing and managing large amounts of data. 
  • Data Integration
    Both involve gathering data from various sources, although an EDW does so at an organizational level. 
  • Analytical Purpose
    Both are designed to support business intelligence, reporting, and analytics, enabling data-driven decisions. 
  • Structured Data
    Both typically store structured data, such as from databases, but can also handle semi-structured data. 
Key Differences (EDW vs. a standard DWH)
  • Scope
    A standard data warehouse is often departmental or focused on a specific business process, while an EDW is designed for the entire organization. 
  • Integration Depth
    An EDW aims to integrate data from many different operational systems (ERPs, CRMs, etc.) across the entire company, rather than from a limited set of sources. 
  • Purpose
    A standard data warehouse provides specific insights for a department, whereas an EDW offers a holistic view of organizational perform
=============================================
Problems / Chellenges of Data modeling ?
Data modeling can face a number of challenges, including:
  • Data quality: Data may be missing, incorrect, or inconsistent, and it can be difficult to maintain data quality over time. 
     
  • Data security: The many interconnected data sources make it vulnerable to attacks from hackers. 
     
  • Integrating diverse data sources: Data from different sources may be in different structures, schemas, and formats. It's important to make sure the data is cleaned and transformed correctly before loading it into a hub. 
     
  • Scalability: Big data can be enormous, and the system may run too slowly or be unable to handle heavy pressure. Cloud computing can help with this challenge. 
     
  • Choosing the right data model: It can be challenging to choose the right data model. 
     
  • Balancing normalization and denormalization: It can be challenging to balance normalization and denormalization. 
     
  • Handling data changes and evolution: It can be challenging to handle data changes and evolution. 
     
  • Communicating and collaborating with stakeholders: It can be challenging to communicate and collaborate with stakeholder

  • ==================================================

SQL UNION vs. UNION ALL.
The key difference is that 
UNION removes duplicate records,
whereas UNION ALL includes all duplicates

=========================================================
DIFFERENCE between joins and union

joins combine data side-by-side, whereas unions combine data one on top of the other
 
===========================================================
Query optimization best practices

When optimizing queries, best practices include: 
 + using indexes effectively, 
+ avoiding SELECT * from ... instead use limit 10 ,
+ filtering data early in the WHERE clause,
+ choosing appropriate JOIN types,
minimizing subqueries ,
utilizing stored procedures,
+ monitoring query performance time,
+ and selecting the correct data typeis instead of varchar and conversion
+ always review and analyze execution plans to identify areas for improvement. 
============================================
Key points to remember:
  • Select only necessary columns:
    Avoid using SELECT * and explicitly list the columns you need to retrieve only the relevant data. 
  • Filter early:
    Apply WHERE clauses as early as possible in the query to reduce the amount of data processed. 
  • Use indexes wisely:
    Create indexes on frequently used columns in WHERE clauses to speed up lookups, but be cautious of over-indexing which can slow down writes. 
  • Optimize joins:
    Choose the appropriate JOIN type (INNER JOIN, LEFT JOIN, etc.) based on your data relationships and avoid unnecessary joins. 
  • Minimize subqueries:
    Try to rewrite queries to avoid nested subqueries where possible as they can be inefficient. 
  • Consider data types:
    Use the most appropriate data type for each column to optimize storage and comparison operations. 
  • Analyze execution plans:
    Regularly review the query execution plan to identify potential bottlenecks and optimize accordingly. 
  • Use stored procedures:
    For complex logic or frequently used queries, consider using stored procedures to improve performance and maintainability. 
Other important practices:
  • Partitioning and sharding:
    For very large datasets, consider partitioning tables by date or other relevant criteria to improve query performance on specific subsets. 
  • Avoid unnecessary calculations:
    Perform calculations only when needed and avoid redundant computations within the query. 
  • Use UNION ALL instead of UNION:
    When combining results from multiple queries, use UNION ALL if you don't need to remove duplicates. 
  • Monitor query performance:
    Implement monitoring tools to track query execution times and identify potential performance issues. 
  • Optimize for your database system:
    Understand the specific optimization features and best practices available for your database platform. 

===============================================

Why do we need Data warehouse when Application database already exists ?

Data warehouses are important for a number of reasons, including:
  • Centralizing data
    Data warehouses consolidate large amounts of data from multiple sources into a single, central database. This makes it easier to analyze the data and gain valuable insights. 
  • Improving decision-making
    Data warehouses help organizations make faster, more informed decisions by providing easy access to high-quality data. 
  • Maintaining historical data
    Data warehouses can store months or years of information, which can be useful for trend analysis and forecasting. 
  • Securing data
    Data warehouses store data in a single location, which makes it easier to control access and keep data secure. 
  • Handling big data
    Data warehouses can help solve big data challenges by making large amounts of information more usable. 
  • Optimizing for read access
    Data warehouses are usually optimized for read access, which can result in faster report generation. 

Data warehouses are a critical component of business intelligence systems and data pipelines
=======================================================
Best Data modeling practices

4 Best Practices for Data Modelling

There are four principles and best practices for data modeling design to help you enhance the productivity of your data warehouse:

Data Modeling Best Practices #1: Grain

Indicate the level of granularity at which the data will be kept. Usually, the least proposed grain would be the starting point for data modeling. Then, you may modify and combine the data to obtain summary insights.

Data Modeling Best Practices #2: Naming

Naming things remains a problem in data modeling. The ideal practice is to pick and adhere to a naming scheme.

Utilize schemas to identify name-space relations, such as data sources or business units. For instance, you might use the marketing schema to hold the tables most relevant to the marketing team, and the analytics schema to store advanced concepts such as long-term value.

Data Modeling Best Practices #3: Materialization

It is one of the most important tools for constructing an exceptional data model. If you build the relation as a table, you may precompute any required computations, resulting in faster query response times for your user base.

If you expose your relation as a view, your users’ queries will return the most recent data sets. Nonetheless, reaction times will be sluggish. Depending on the data warehousing strategy and technologies you employ, you may have to make various trade-offs according to actualization.

Data Modeling Best Practices #4: Permissions and Governance

Data modelers should be aware of the varying rights and data governance requirements of the enterprise. Working collaboratively with your security team to verify that your data warehouse adheres to all applicable regulations would be beneficial.

For instance, firms that deal with medical data sets are subject to HIPAA data authorization and privacy rules. All customer-facing internet firms should be aware of the EU General Data Protection Regulation (EU GDPR), and SaaS enterprises are frequently constrained in their ability to exploit client data depending on the terms of their contracts.

=======================================================
where do we use data vault modeling

A data vault is a data modeling approach and methodology used in enterprise data warehousing to handle complex and varying data structures. It combines the strengths of 3rd normal form and star schema.
===============================================================


No comments:

Post a Comment

73 ) Sql Query optimization steps

  Sample Improperly Constructed Complex Query (Anti-Pattern Example) SQL SELECT DISTINCT UPPER (r.RegionName) AS RegionName, ...