SQL Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Tue, 19 Dec 2023 05:34:58 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 SQL Archives - Tech Insights 32 32 230003556 How to Get the size of all Tables in a Database https://reactconf.org/sql-server-get-size-of-all-tables-in-a-database/ https://reactconf.org/sql-server-get-size-of-all-tables-in-a-database/#respond Tue, 19 Dec 2023 05:34:58 +0000 http://www.sqlneed.com/?p=534 In this guide, we will learn How to Get the size of all Tables in a Database using SQL Server. There are multiple ways, let’s take a look at them …

The post How to Get the size of all Tables in a Database appeared first on Tech Insights.

]]>
In this guide, we will learn How to Get the size of all Tables in a Database using SQL Server. There are multiple ways, let’s take a look at them one by one.

#Solution-1: SQL Query

The query joins information from the system catalog views such as “sys.tables”, “sys.indexes”, ”sys.partitions”, and “sys.allocation_units” to calculate the size of each table in KB(kilobytes) and as well as MB(megabytes).

It provides a detailed overview of all tables in the specified database, including the table name row count, total size, used size, and unused side. The results are ordered by total size in descending order, so you can easily identify the largest tables.

SELECT 
    t.name AS TableName,
    s.name AS SchemaName,
    p.rows,
    SUM(a.total_pages) * 8 AS TotalSpaceInKB, 
    CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceInMB,
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceInMB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceInKB,
    CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceInMB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.object_id = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.object_id AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.name NOT LIKE 'dt%' 
    AND t.is_ms_shipped = 0
    AND i.object_id > 255 
GROUP BY 
    t.name, s.name, p.rows
ORDER BY 
    TotalSpaceInMB DESC, t.name;

Results:

How to Get size of all Tables in a Database

#Solution-2:CTE Query

with CTE as (  
  SELECT  
  t.name as TableName,  
  SUM (s.used_page_count) as used_pages_count,  
  SUM (CASE  
              WHEN (i.index_id < 2) THEN (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)  
              ELSE lob_used_page_count + row_overflow_used_page_count  
          END) as pages  
  FROM sys.dm_db_partition_stats  AS s   
  JOIN sys.tables AS t ON s.object_id = t.object_id  
  JOIN sys.indexes AS i ON i.[object_id] = t.[object_id] AND s.index_id = i.index_id  
  GROUP BY t.name  
  )  
  ,cte2 as(select  
      cte.TableName,   
      (cte.pages * 8.) as TableSizeInKB,   
      ((CASE WHEN cte.used_pages_count > cte.pages   
                  THEN cte.used_pages_count - cte.pages  
                  ELSE 0   
            END) * 8.) as IndexSizeInKB  
  from CTE  
 )  
 select TableName,TableSizeInKB,IndexSizeInKB,  
 case when (TableSizeInKB+IndexSizeInKB)>1024*1024   
 then cast((TableSizeInKB+IndexSizeInKB)/1024*1024 as varchar)+'GB'  
 when (TableSizeInKB+IndexSizeInKB)>1024   
 then cast((TableSizeInKB+IndexSizeInKB)/1024 as varchar)+'MB'  
 else cast((TableSizeInKB+IndexSizeInKB) as varchar)+'KB' end [TableSizeIn+IndexSizeIn]  
 from CTE2  
 order by 2 desc

Result:

How to Get size of all Tables in a Database

#Solution-3:T-SQL |Stored Procedure

-- Using T-SQL
DECLARE @table_name sysname 
DECLARE table_list_cursor 
CURSOR FOR SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES 
where TABLE_TYPE='BASE TABLE' 
IF EXISTS ( SELECT * FROM    tempdb.INFORMATION_SCHEMA.COLUMNS WHERE    table_name = '##TABLE_RES')
BEGIN    
DROP TABLE ##TABLE_RES END CREATE TABLE ##TABLE_RES( Name nvarchar(255), 
Rows int, reserved varchar(18), Data varchar(18), index_size varchar(18),
Unused varchar(18)) OPEN table_list_cursor 
FETCH NEXT FROM table_list_cursor INTO @table_name 
INSERT INTO ##TABLE_RES exec sp_spaceused @table_name
WHILE @@FETCH_STATUS = 0 
BEGIN    FETCH NEXT FROM table_list_cursor INTO @table_name
INSERT INTO ##TABLE_RES exec sp_spaceused @table_name 
END CLOSE table_list_cursor 
DEALLOCATE table_list_cursor 
SELECT * from ##TABLE_RES order by rows desc
How to Get size of all Tables in a Database

#Solution-4: To Get the size of all tables in the SQL Server Database

In SQL Server, it is an easier way to get the size of all tables in the database is to use the Standard Report feature available in SQL Server Management Studio.

  • Open the SSMS (SQL Server Management Studio)
  • Now, Right Click on the Selected Database.
  • Select Reports
  • Next, Select Standard Reports
  • Then Click on Disk Usage by Table
How to Get size of all Tables in a Database using SQL Server

Output:

See Also:

The post How to Get the size of all Tables in a Database appeared first on Tech Insights.

]]>
https://reactconf.org/sql-server-get-size-of-all-tables-in-a-database/feed/ 0 534
How to Find All Identity Columns in the Database https://reactconf.org/find-all-identity-columns-in-the-database/ https://reactconf.org/find-all-identity-columns-in-the-database/#respond Sat, 04 Nov 2023 09:16:06 +0000 http://www.sqlneed.com/?p=573 In this article, we will learn How to Find all Identity Columns in the Database. You can typically query the system catalog or information schema, to find identity columns in …

The post How to Find All Identity Columns in the Database appeared first on Tech Insights.

]]>
In this article, we will learn How to Find all Identity Columns in the Database. You can typically query the system catalog or information schema, to find identity columns in different database management systems.

Here’s a Query to find all identity columns in a database.

Using SQL Server to Find All Identity Columns in the Database

SELECT 
	OBJECT_SCHEMA_NAME(tables.object_id, db_id())
	AS SchemaName,
	tables.name As TableName,
	columns.name as ColumnName
FROM sys.tables tables 
	JOIN sys.columns columns 
ON tables.object_id=columns.object_id
WHERE columns.is_identity=1

This query retrieves the table and column names of identity columns in a Database.

Find All identity columns in the database

Another way to find all identity columns in the Database. It contains details of all identity columns in a database along with their seed value, increment value, and other information. The below query for the same is given.

SELECT 
	OBJECT_SCHEMA_NAME(tables.object_id, db_id())
	AS SchemaName,
	tables.name As TableName,
	identity_columns.name as ColumnName,
	identity_columns.seed_value,
	identity_columns.increment_value,
	identity_columns.last_value
FROM sys.tables tables 
	JOIN sys.identity_columns identity_columns 
ON tables.object_id=identity_columns.object_id
Find All Identity Columns in the Database

Read Also:

The post How to Find All Identity Columns in the Database appeared first on Tech Insights.

]]>
https://reactconf.org/find-all-identity-columns-in-the-database/feed/ 0 573
How to Implement Join Operations in Django ORM https://reactconf.org/how-to-implement-join-operations-in-django-orm/ https://reactconf.org/how-to-implement-join-operations-in-django-orm/#respond Mon, 17 Apr 2023 01:43:29 +0000 https://labpys.com/?p=1061 You will probably need to work with a database at some point if you are using Django to create a web application.  Django Object Relational Mapping(ORM), makes this process easier …

The post How to Implement Join Operations in Django ORM appeared first on Tech Insights.

]]>
You will probably need to work with a database at some point if you are using Django to create a web application. 

Django Object Relational Mapping(ORM), makes this process easier by allowing you to work with Python classes instead of SQL queries.

Joining two or more tables to extract relevant data is one of the most common tasks when working with a database. We will look into joining tables with Django ORM in this tutorial.

Database Relationships

Before we dig into joining tables, it is essential to understand the different types of relationships that can exist between tables in a database. The three most common types of relationships are.

  • One-to-one(1:1)  – Each record in one table is related to one and only one record in another table.
  • One-to-many(1:N) – Each record in one table is related to zero, one, or many records in another table.
  • Many-to-Many(N: N) – Each record in one table is related to zero, one, or many records in another table and vice versa.

Create Django Join

Create a Project

First, we need to create a project by running the following commands in your terminal or command prompt

Django-admin startproject Joins_ORM

Create an app

A Django project consists of one or more apps. Creating a new app by running the following command in your terminal or command prompt

Python manage.py startapp jointable

Create a Model

from django.db import models

# Create your models here.

class Author(models.Model):
    FirstName = models.CharField(max_length=100)
    LastName = models.CharField(max_length=100)
    MiddleName = models.CharField(max_length=100)

class Books(models.Model):
    title = models.CharField(max_length=200)
    total_page = models.IntegerField()
    auth_id = models.ForeignKey(Author, on_delete=models. CASCADE)
    

Django Join Tables Using ORM

INNER JOIN

from django.shortcuts import render
from .models import Books,Author

# Create your views here.

def jointable(request):
    books = Books.objects.select_related('auth_id').filter(title='A Better World')

    return render(request,'index.html',{'context':books})

LEFT JOIN

def Leftjoin(request):

    books = Books.objects.filter(Q(auth_id__isnull=True)|Q(auth_id__isnull=False))   
    return render(request,'index.html',{'context':books})

RIGHT JOIN

def Rightjoin(request):

    books = Books.objects.select_related('auth_id').all()

    return render(request,'index.html',{'context':books})

See More How to Add Pagination

The post How to Implement Join Operations in Django ORM appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-implement-join-operations-in-django-orm/feed/ 0 1061
How to Find Top N records using SQL https://reactconf.org/how-to-find-top-n-records-using-sql/ https://reactconf.org/how-to-find-top-n-records-using-sql/#respond Wed, 12 Oct 2022 10:15:15 +0000 http://www.sqlneed.com/2022/10/how-to-find-top-n-records-using-sql/ In this article we will see how to Find Top N records using SQL Server. Top –N queries that limit the result set to a specific number of rows.  Top …

The post How to Find Top N records using SQL appeared first on Tech Insights.

]]>

In this article we will see how to Find Top N records using SQL Server. Top –N queries that limit the result set to a specific number of rows. 

Top N Without Grouping

Top N Without Grouping – in this query its get the department wise employee list with grouping.

Select top 3 d.GroupName,e.JobTitle, p.Firstname,p.Lastname  from [Person].[Person] p inner join [HumanResources].[Employee] e 
on(p.BusinessEntityID = e.BusinessEntityID) inner join  [HumanResources].[EmployeeDepartmentHistory] h
on(e.BusinessEntityID=h.BusinessEntityID) inner join [HumanResources].[Department] d on(d.DepartmentID=h.DepartmentID)

Example-2

Top N With Grouping

Top N With Grouping – Its fetch the department wise employee list with grouping.

select  d.GroupName,e.JobTitle, p.Firstname,p.Lastname ,
ROW_NUMBER() over (partition by d.groupname order by d.groupname asc) as department_rank 
from [Person].[Person] p inner join [HumanResources].[Employee] e 
on(p.BusinessEntityID = e.BusinessEntityID) inner join  [HumanResources].[EmployeeDepartmentHistory] h
on(e.BusinessEntityID=h.BusinessEntityID) inner join [HumanResources].[Department] d on(d.DepartmentID=h.DepartmentID)

The post How to Find Top N records using SQL appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-find-top-n-records-using-sql/feed/ 0 2243