Wednesday, June 14, 2023

The Simple-Talk Editors Blog

Today I am starting (well, restarting) a new feature here on Simple-Talk, The Editor’s Blog. This blog will cover topics about writing technical blogs and articles, how to access the information on Simple-Talk at your convenience, and even other writing issues like how to write an excellent presentation and abstract. Topics will sometimes be Simple-Talk centric, but more often, subjects will be about writing and editing content that I think will be useful to anyone. 

I aim to separate the editorial content from the technical content I want to write. There have been editors before me, and there will almost certainly be editors after. Still, the content of the editor of Simple-Talk will generally be timeless content and valuable no matter who is writing or editing it.

I (Louis Davidson, current editor and an owner of a desk that usually wishes it was that neat) have had a blog on Simple-Talk for many years before working at Redgate and will continue to post technical articles, slightly personal editorials, and announcements as to where I will be speaking and attending conferences and user group meetings. Mixing this in with editor content seemed wrong. 

Buried in the structures of the Simple-Talk website, there are articles about how to write an article, style guides, writing an influential blog, etc. I want to move them forward as blog posts that are easy to access. Most of the points in these articles are valid for blogs we publish on Simple-Talk and other places too. From time to time, I might update that data as well.

In the future, more general articles about writing, speaking, or content production that can help our writers and the community will appear.

 Image from: https://www.pexels.com/photo/photo-of-an-abandoned-workspace-3359003/

 

The post The Simple-Talk Editor’s Blog appeared first on Simple Talk.



from Simple Talk https://ift.tt/E5jsuKM
via

Unmasking SQL Server Dynamic Data Masking Part 3 Security Concerns

This is the third part of a series on SQL Server Dynamic Data Masking. The first part in the series was a brief introduction to dynamic data masking, completing solutions, and use cases. The second part covered setting up masking and some examples. This part starts exploring side channel attacks against dynamic data masking.

This article will show that are plenty of security concerns with using Dynamic Data Masking as a general-purpose security tool, but don’t let it completely keep you from using it. The point of the article is to show you the weakness of the tool, particularly for ad-hoc uses with users who might be keen to snoop around the data in ways you might not expect.

There are a lot of ways that users can decode data that is only dynamically masked, and in the next two entries in this series I want to show some of those methods, not to show you HOW to decode masked data, but for two reasons.

  1. To show you why dynamic data masking should not be used to mask very personal data that might be stolen, especially when you do not have tight control over the users.
  2. To help you notice if your users might be doing some of these things.

Side Channel Attacks

When SQL Server 2016 was announced, dynamic data masking was an exciting part of the offering from a security and business intelligence perspective. Allowing end users to access data while masking critical data is a boon. It eliminates the need for custom solutions and makes it possible to expose useful data in a safe manner. The documentation for this feature had a few lines, warnings really, about the possibility of side channel attacks. I had heard of side channel attacks in regard to the operating system and other products but didn’t exactly understand how it applied to masking. The basic examples made sense, but I needed to understand the limits of this to evaluate it properly and see how it might fit into existing architectures.

The real question was, how do these side channel attacks work and what is the scope of their vulnerability? Examples of these attacks are a little sparse. I’m sure some of the paucity of information is explained by security by obfuscation. The best way to find out the vulnerabilities was to carefully test them. The basic test bed is as follows.

  • An unaltered version of WideWorldImporters
  • An account with dbo access
  • A test account with SELECT only access
  • Individual columns were masked

With the test bed created the ability to derive clear text data from the masked data was analyzed.

Exploratory Scripts

Unmasking data starts with finding masked columns. This is a simple flag in the standard system views. The Microsoft documentation also shows a masked column system view (sys.masked_columns), but you have fewer filtering options and it can be helpful to view both masked and unmasked columns together. A likely starting point on a production system is finding a column that is masked during normal data exploration and operations. The standard version of the sample database used, WideWorldImporters, has 5 columns masked in the Purchasing.Suppliers table and the same columns in the associated temporal table masked. If your version of the database starts without these columns masked, you have a different version of the database. After running the setup script to mask columns (which you can find at the end of Part 1 here), there are a total of 38 columns masked. After you restore WorldWideImporters, run both the security and alter scripts included.

USE WideWorldImporters
GO
SET NOCOUNT ON
GO
/*
* Script to show masked columns
* Data type, length, and masking function are included.
*
* The base system views are used rather than the masked
* column DMV so additional filters can be used
* or all columns can be shown, but the masked column DMV
* is used to show the mask function.
*
* Note that users with db_datareader rights 
* can still access
* the necessary metadata to run this script.
*/
EXECUTE AS USER = 'MaskedReader'
GO
SELECT
    SS.name            SchemaName
    ,SO.name        TableName
    ,SC.name        ColumnName
    ,SC.is_masked    ColumnIsMasked
    ,ST.name        ColumnDataType
    ,CASE 
        WHEN st.max_length = -1 THEN 0
        WHEN st.name IN ('nchar','nvarchar') 
   THEN SC.max_length / 2
        WHEN st2.name IN ('nchar','nvarchar') 
   THEN SC.max_length / 2
        ELSE SC.max_length
    END    MaxLength
    ,st.precision
    ,st.scale
    ,M.masking_function
FROM sys.objects SO
    INNER JOIN sys.columns SC
        ON so.object_id = sc.object_id
    INNER JOIN sys.schemas SS
        ON so.schema_id = ss.schema_id
    INNER JOIN sys.types ST
        ON SC.system_type_id = ST.system_type_id
        AND SC.user_type_id    = ST.user_type_id
    LEFT JOIN sys.types st2
        ON st.system_type_id = st2.system_type_id 
        AND st2.system_type_id = st2.user_type_id
        AND st.is_user_defined = 1
    LEFT JOIN sys.masked_columns M
        ON SC.object_id = M.object_id
        AND SC.column_id = M.column_id
WHERE SC.is_masked = 1
ORDER BY
    SS.name
    ,SO.name
    ,SC.name;
GO
REVERT;
GO

The exploratory script shows the schema, table and column that is masked. It also shows details about the column, including data type, and the function used to mask the data. This is very useful information for administrators, developers, support, and also bad actors. 

Partial Unmasking

Unmasking a portion of the data in a column, partial unmasking, can be done easily. This is a function of dynamic data masking, expected functionality, so no surprise here. Without the ability to partially unmask data (categorize data), masking becomes much less useful in a production environment. The only trick to unmasking this way is organizing it in a fashion that makes it more useful or interesting. Creating and assigning artificial categories is the most obvious way to look at data in this way. Broad categories, such as a min / max with an interval of 1000, can be very useful for quick analysis and still expose data. These categories can effectively negate the entire purpose of masking. It would be no help for an ID column, but it would be very damaging for things like salary or bank account balances. This is a good reminder to analyze your business need carefully before exposing data, even with masking.

USE WideWorldImporters
GO
SET NOCOUNT ON
GO
/*
* Example showing how numeric data can be categorized
* into broad categories.
* The functional use of this in normal processing, is to 
* create the bins / buckets (categories) for a histogram.
*
* The ability to evaluate masked data at this level is also
* a potential gap in expected security.
*/
EXECUTE AS USER = 'MaskedReader'
GO
/*
* Script assumes no pre-existing tables other than
* those in the sample database. A numbers table is
* generated via a recursive CTE.
* The size of the buckets is determined by the 
* recursive column (N + 1000)
* This can be changed to any size bucket, including 1
*/
;
WITH NUMBERS_CTE AS (
    SELECT 0 AS N
        UNION ALL
    SELECT N + 1000
    FROM NUMBERS_CTE
    WHERE N < 2000000
)
,MIN_MAX_CTE AS (
    SELECT
        N            MinNumber
        ,N + 1000    MaxNumber
    FROM NUMBERS_CTE
)
/*
* Masked data and data placed into buckets are returned
* Each masked column is joined to the numbers table
* using the minimum and the maximum of the category
* for each join.
*
* Order specified using OutstandingBalance DESC to show
* more populated data first for the example.
*
* OPTION(MAXRECURSION 0) is used to allow recursion 
* beyond 100 levels. * 0 puts no limit on the recursion. 
* It is used for simplicity but the actual limit could be 
* used in place of 0 to ensure an infinite loop isn't created.
* https://learn.microsoft.com/sql/t-sql/queries/with-common-table-expression-transact-sql
*/
SELECT
    SupplierID
    ,TransactionTypeID
    ,PurchaseOrderID
    ,TransactionAmount
    ,OutstandingBalance
    ,N.MinNumber            TransactionAmountMin
    ,N.MaxNumber            TransactionAmountMax
    ,N2.MinNumber            OutstandingBalanceMin
    ,N2.MaxNumber            OutstandingBalanceMax
FROM Purchasing.SupplierTransactions STT
    LEFT JOIN MIN_MAX_CTE N
        ON STT.TransactionAmount 
            BETWEEN N.MinNumber AND N.MaxNumber
    LEFT JOIN MIN_MAX_CTE N2
        ON STT.OutstandingBalance 
            BETWEEN N2.MinNumber AND N2.MaxNumber
WHERE TransactionAmount        IS NOT NULL
ORDER BY OutstandingBalance DESC
OPTION(MAXRECURSION 0)
GO
REVERT
GO

The output shows the primary key, foreign key columns, and the two masked columns, in addition to their values as ranges. It is safe to assume that the data in the bottom range, 0-1000 is likely 0. This could be validated by using a WHERE clause and only returning rows WHERE OutstandingBalance = 0.

 

This works well with numeric data. The next test is character data. Since functions like substrings and wildcard searches are operational with masked data, grouping data is straight forward.

USE WideWorldImporters
GO
SET NOCOUNT ON
GO
/*
* Example showing how string data can be categorized
* into broad categories.
* 
* This is a similar security gap shown in the numeric data
*/
EXECUTE AS USER = 'MaskedReader'
GO
/*
* Script assumes no pre-existing tables other than
* those in the sample database. A numbers table is
* generated via a recursive CTE.
*
* The number table is limited to 255 characters to cover
* the standard ASCII character set.
*
* The full unicode character set could be traversed, but it would take
* more time.
*
* The columns are combined via a cross join to 
* get all possible ASCII combinations for two columns.
*/
WITH NUMBERS_CTE AS (
    SELECT 1 AS N
        ,CHAR(1) AS CharN
        UNION ALL
    SELECT N + 1
        ,CHAR(N+1)
    FROM NUMBERS_CTE
    WHERE N < 255
)
,CHAR_CTE AS (
    SELECT
        N1.CharN + N2.CharN CharN
    FROM NUMBERS_CTE N1
        CROSS JOIN NUMBERS_CTE N2
)
/*
* Data from the masked columns is joined to 
* the recursive CTE to find the first two unmasked values.
* 
* The collation is specified to handle any 
* potential collation mismatches
*/
SELECT
    C.CustomerID
    ,C.CustomerName
    ,N.CharN            CustomerName_MaskStart
    ,C.DeliveryAddressLine1
    ,N2.CharN            DeliveryAddressLine1_MaskStart
    ,C.DeliveryAddressLine2
    ,N3.CharN            DeliveryAddressLine2_MaskStart
    ,C.DeliveryPostalCode
    ,N4.CharN            DeliveryPostalCode_MaskStart
FROM Sales.Customers C
    LEFT JOIN CHAR_CTE N
        ON SUBSTRING(C.CustomerName,1,2) 
                COLLATE SQL_Latin1_General_CP1_CS_AS    
             = N.CharN COLLATE SQL_Latin1_General_CP1_CS_AS
    LEFT JOIN CHAR_CTE N2
        ON SUBSTRING(C.DeliveryAddressLine1,1,2) 
                 COLLATE SQL_Latin1_General_CP1_CS_AS    
             = N2.CharN COLLATE SQL_Latin1_General_CP1_CS_AS
    LEFT JOIN CHAR_CTE N3
        ON SUBSTRING(C.DeliveryAddressLine2,1,2) 
                COLLATE SQL_Latin1_General_CP1_CS_AS    
             = N3.CharN COLLATE SQL_Latin1_General_CP1_CS_AS
    LEFT JOIN CHAR_CTE N4
        ON SUBSTRING(C.DeliveryPostalCode,1,2) 
                COLLATE SQL_Latin1_General_CP1_CS_AS    
             = N4.CharN COLLATE SQL_Latin1_General_CP1_CS_AS
WHERE CustomerID > 800
ORDER BY CustomerID
OPTION(MAXRECURSION 0);
GO
REVERT
GO

 

Output shows the key columns, the masked columns, and the partially unmasked columns. Remember that if specific values are wanted, they can be targeted by using the initial partial unmasking to narrow down choices.

 

Using this tactic would allow a bad actor to start chipping away at specific values. If you were interested in a particular client name or individual, this technique allows masked values to be targeted rather quickly. If a particular client name was known, it could be specified in a script to find the row even faster. If the data is completely unknown when you begin your process, it is an effective, but more prolonged, technique.

USE WideWorldImporters;
GO
EXECUTE AS USER = 'MaskedReader';
GO
SELECT *
FROM Sales.Customers
WHERE CustomerName = 'Amrita Ganguly';
GO
REVERT;
GO

The targeted record will be returned, even if the WHERE criteria is for the masked column. This is intentional to the implementation of dynamic data masking, and required for it to work correctly, even if it seems like a potential security gap. 

Automated Partial Unmasking

Partial unmasking categories are relatively easy to create. The part that requires thought is deciding where to create the intervals. If you understand the data it is easy. If the data is unknown, it requires some initial exploration. This is also a good demonstration of layered security. This table comes with row level security (RLS) enabled in the sample database. RLS adds another layer of security to configured tables, restricting access to specified rows. There are several ways RLS can be implemented, and in this case the database uses the SalesTerritory table for a city to determine access levels. If the user is in the associated database user role, they are able to retrieve those rows. The user for this example was given partial access by adding MaskedReader to the [External Sales] role, so only those rows are returned. Functions and comparison operators are used on the masked column. In the user creation script, the following command grants access via RLS. Refer to the Filter Predicate [Application].[DetermineCustomerAccess] in the database for details.

The Azure, basic version, of the database does not include RLS and the following script will fail. The full version of the database includes RLS and the role is available.

USE WideWorldImporters;
GO
ALTER ROLE [External Sales]
ADD MEMBER MaskedReader;
GO
USE WideWorldImporters;
GO
SET NOCOUNT ON;
GO
/*
* Example showing static histogram bucket generation.
* Also shows how functions and comparison operators
* can be used directly on columns.
*/
EXECUTE AS USER = 'MaskedReader';
GO
SELECT
    CustomerID
    ,CreditLimit
    ,CASE 
        WHEN CreditLimit > 3000 THEN '3000+'
        WHEN CreditLimit > 2500 THEN '2500+'
        WHEN CreditLimit > 2000 THEN '2000+'
        WHEN CreditLimit > 1500 THEN '1500+'
        WHEN CreditLimit > 1000 THEN '1000+'
        ELSE '>1000'
    END CreditLimitHistogram
FROM Sales.Customers
WHERE CreditLimit IS NOT NULL
ORDER BY CustomerID;
GO
REVERT;
GO

The histogram buckets are returned very quickly. The number and range of buckets can be easily modified for the specific data and scenario.

 

Finding number ranges automatically

Finding number ranges for a histogram is as easy as joining to an unmasked table. A standard numbers table works well. Specialized numbers tables can be created to tackle known or unusual columns.

Histogram bucket generation can be automated using a standard or specialized number tables. If you have a reasonable guess for the max or the ranges, the composition of the number table can be tailored to the target table. If the masked column contains latitude and longitudes, a standard number table would work for initial exploration. Multiplying the number by 10000 to get the desired accuracy would still work with a standard number table and would identify objects to within 11 meters (according to the GIS wiki, a decimal accurate to 4 decimal places will achieve this result).

USE WideWorldImporters;
GO
SET NOCOUNT ON;
GO
/*
* Dynamic creation of a script to create histogram 
* buckets for a masked column. 
*
* The schema, table, and column are manually specified.
* If the object and column specified is not correct, an error 
* will be returned
* 
* Run the script with @EXECUTE = 0, in text mode 
*(<crtrl> + T) in SSMS to see the script that is generated
* rather than running it.
*/
EXECUTE AS USER = 'MaskedReader';
GO
/**********************************************************
* Declare and set the variables for this run 
**********************************************************/
DECLARE
    @ServerName varchar(255)= 'localhost' --@@SERVERNAME
    ,@SchemaName varchar(255) = 'Purchasing'
    ,@TableName varchar(255) = 'SupplierTransactions'
                --'SuppliersTest' 
                --'SupplierTransactions'
   ,@HistogramColumn varchar(255) = 'TransactionAmount'
   ,@EXECUTE tinyint = 1 -- 1 = execute, 0 = print
   ,@NOLOCK tinyint = 1   --1 = WITH(NOLOCK), 
--        --0 = default lock (committed)
   ,@SQL varchar(max)
/*********************************************************
* Primary Key Columns
*
* The sample script requires a primary key column for 
* it to work automatically. The primary key columns for the 
* table specified are dynamically inserted into @PrimaryKeys 
* using system tables.
**********************************************************/
DECLARE @PrimaryKeys TABLE (
    PrimaryKeyName sysname
   ,ColumnName sysname
   ,RowNumber int identity
)
INSERT INTO @PrimaryKeys (
   PrimaryKeyName
   ,ColumnName
)
EXEC('
SELECT
    si.name  PrimaryKeyName
   ,sc.name  ColumnName
FROM sys.objects so
    INNER JOIN sys.schemas ss
      ON so.schema_id = ss.schema_id
    INNER JOIN sys.indexes si
      ON so.object_id = si.object_id
    INNER JOIN sys.index_columns ic
      ON so.object_id = ic.object_id
        AND si.index_id    = ic.index_id
    INNER JOIN sys.columns sc
      ON ic.object_id = sc.object_id
        AND ic.index_column_id = sc.column_id
    WHERE so.name = ' + '''' + @TableName + '''' + '
        AND ss.name = ' + '''' + @SchemaName + '''' + '
        AND SI.is_primary_key = 1
ORDER BY 
    sc.column_id
')
/* If no PK columns are found, exit */
IF (SELECT COUNT(*) FROM @PrimaryKeys) = 0
BEGIN
    GOTO NO_EXECUTE
END
/***********************************************************
* SQL Statement
*
* Dynamic version of the previous script.
* the Number CTE is created first.
************************************************************/
SELECT @SQL = '
' + CASE @NOLOCK 
      WHEN 1 
      THEN 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
'
ELSE ''
END
SELECT @SQL += '
;
WITH NUMBERS_CTE AS (
    SELECT 0 AS N
        UNION ALL
    SELECT N + 1000
    FROM NUMBERS_CTE
    WHERE N < 2000000
)
,MIN_MAX_CTE AS (
    SELECT
        N MinNumber
        ,N + 1000    MaxNumber
    FROM NUMBERS_CTE
)
'
/* 
* Static columns are specified, then the primary key columns
* Then the specified masked column is added as the MIN and MAX
* from the subsequent JOIN to the numbers table.
*/
SELECT @SQL += '
SELECT
    ' + '''' + @ServerName + '''' + ' SERVER_NAME
    ,' + '''' + DB_NAME() + '''' + ' DATABASE_NAME
    ,' + '''' + @SchemaName + '''' + ' SCHEMA_NAME
    ,' + '''' + @TableName + '''' + ' TABLE_NAME'
SELECT @SQL += '
    ,MC.' + ColumnName
FROM @PrimaryKeys
SELECT @SQL += '
    ,' + @HistogramColumn
SELECT @SQL +=
    '
    ,N.MinNumber ' + @HistogramColumn + '_MIN
    ,N.MaxNumber ' + @HistogramColumn + '_MAX'
SELECT @SQL += '
FROM [' + @SchemaName + '].[' + @TableName + '] MC WITH (NOLOCK)'
SELECT @SQL +=
'
    LEFT JOIN MIN_MAX_CTE N' + '
        ON MC.' + @HistogramColumn + ' BETWEEN N' + 
   '.MinNumber AND N' + '.MaxNumber '
SELECT @SQL += '
ORDER BY'
SELECT @SQL += 
    CASE RowNumber
        WHEN 1 THEN '
    MC.' + ColumnName 
        ELSE '
    ,MC.' + ColumnName
    END
FROM @PrimaryKeys
SELECT @SQL += '
OPTION(MAXRECURSION 0);
'
BEGIN TRY
    IF @EXECUTE = 1
    BEGIN
        EXEC(@SQL)
    END
    ELSE SELECT @SQL
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
NO_EXECUTE:
GO
REVERT;
GO

The automatically generated ranges are shown below, in addition to the key column and the table name. The output can be analyzed exactly as in the previous example.

USE WideWorldImporters;
GO
SET NOCOUNT ON;
GO
/*
* Dynamic creation of a script to create histogram 
* buckets for all masked columns in a table. 
*
* The schema and table are manually specified. If the 
* object specified is not correct, an error will be 
* returned
* 
* Run the script with @EXECUTE = 0, in text mode 
* (<ctrl> + T) in SSMS to see the script that is 
* generated rather than running it.
*
* Setting the @SHOW_COLUMNS_ONLY to 1 will display 
* the masked columns and exit
*
* If any columns should be ignored during the process,
* specify them in @Exclude as a comma separated list.
*/
EXECUTE AS USER = 'MaskedReader'
GO
/**********************************************************
* Declare and set the variables for this run 
***********************************************************/
DECLARE
    @ServerName   varchar(255) = 'localhost' --@@SERVERNAME
    ,@SchemaName  varchar(255) = 'Purchasing'
    ,@TableName  varchar(255) = 'SupplierTransactions'    
      --'SuppliersTest' --'SupplierTransactions'
    ,@PrimaryKey  varchar(255)  = NULL  --'SupplierName'
    ,@EXECUTE tinyint  = 1  -- 1 = execute, 0 = print
    ,@NOLOCK  tinyint = 1  
         --1 = WITH(NOLOCK), 0 = default lock (committed)
    --,@strStandardFlag  varchar(20)
    --,@strStandardCode  varchar(20)
    ,@SHOW_COLUMNS_ONLY  bit = 0
      --1 = columns only and exit, 0 = don't show column list
    ,@Exclude  varchar(500)         
          --= 'BankAccountBranch,BankAccountCode' 
          --CSV list of columns that will be ignored
/********************************************************
* Temporary table definitions
********************************************************/
DECLARE @Columns TABLE (
    ColumnID    int
    ,ColumnName    varchar(255)
)
/*********************************************************
* Variables set internally
**********************************************************/
DECLARE
    @HasText    tinyint
    ,@SQL        varchar(max)
    ,@OrderList    varchar(max)
/*********************************************************
* Set the columns to include
*
* Find masked, numeric columns in the table specified.
* Add them to the @Columns table variable
*********************************************************/
INSERT INTO @Columns
EXEC (
    'SELECT 
        SC.column_id
        ,SC.name
    FROM sys.objects SO
        INNER JOIN sys.columns SC
            ON so.object_id = sc.object_id
        INNER JOIN sys.schemas SS
            ON so.schema_id = ss.schema_id
        INNER JOIN sys.types ST
            ON SC.system_type_id    = ST.system_type_id
            AND SC.user_type_id        = ST.user_type_id
        LEFT JOIN string_split(' + '''' + @Exclude + '''' + ',' + '''' + ',' + '''' + ') SSTR
            ON SC.name COLLATE SQL_Latin1_General_CP1_CI_AS             = SSTR.value COLLATE SQL_Latin1_General_CP1_CI_AS 
    WHERE so.name COLLATE SQL_Latin1_General_CP1_CI_AS = ' + '''' + @TableName + '''' + ' COLLATE SQL_Latin1_General_CP1_CI_AS 
        AND ss.name COLLATE SQL_Latin1_General_CP1_CI_AS = ' + '''' + @SchemaName + '''' + ' COLLATE SQL_Latin1_General_CP1_CI_AS 
        AND ST.system_type_id NOT IN (240)
        AND SC.is_masked                = 1
        AND SSTR.value    IS NULL
        AND ST.name IN (' + '''' + 'tinyint' + '''' 
            + ','  + '''' + 'smallint' + ''''
            + ','  + '''' + 'int' + ''''
            + ','  + '''' + 'bigint' + ''''
            + ','  + '''' + 'decimal' + ''''
            + ','  + '''' + 'numeric' + ''''
            + ','  + '''' + 'float' + ''''
            + ','  + '''' + 'real' + ''''
            + ','  + '''' + 'money' + ''''
        + ')
    ORDER BY sc.name'
)
IF @SHOW_COLUMNS_ONLY = 1
BEGIN
    SELECT * FROM @Columns
    GOTO NO_EXECUTE
END
IF (SELECT COUNT(*) FROM @Columns) = 0
BEGIN
    RAISERROR('No columns present: Check that you are running the script from the correct database, that the name of the table is correct and that you have permission to select from the table.',5,1)
    GOTO NO_EXECUTE
END
/**********************************************************
* Primary Key Columns
*
* The sample script requires a primary key column for it to work
* automatically. The primary key columns for the table specified
* are dynamically inserted into @PrimaryKeys using system tables.
***********************************************************/
DECLARE @PrimaryKeys TABLE (
    PrimaryKeyName  sysname
    ,ColumnName    sysname
    ,RowNumber  int identity
)
INSERT INTO @PrimaryKeys (
    PrimaryKeyName
    ,ColumnName
)
EXEC('
SELECT
    si.name    PrimaryKeyName
    ,sc.name    ColumnName
FROM sys.objects so
    INNER JOIN sys.schemas ss
        ON so.schema_id = ss.schema_id
    INNER JOIN sys.indexes si
        ON so.object_id = si.object_id
    INNER JOIN sys.index_columns ic
        ON so.object_id = ic.object_id
        AND si.index_id    = ic.index_id
    INNER JOIN sys.columns sc
        ON ic.object_id = sc.object_id
        AND ic.index_column_id = sc.column_id
    WHERE so.name COLLATE SQL_Latin1_General_CP1_CI_AS = ' + '''' + @TableName + '''' + ' COLLATE SQL_Latin1_General_CP1_CI_AS
        AND ss.name COLLATE SQL_Latin1_General_CP1_CI_AS = ' 
             + '''' + @SchemaName + '''' + ' 
                      COLLATE SQL_Latin1_General_CP1_CI_AS
        AND SI.is_primary_key = 1
ORDER BY 
    sc.column_id
')
IF (SELECT COUNT(*) FROM @PrimaryKeys) = 0
BEGIN
    IF @PrimaryKey IS NULL GOTO NO_EXECUTE
    ELSE
    BEGIN
        INSERT INTO @PrimaryKeys (PrimaryKeyName,ColumnName)
        VALUES (@PrimaryKey,@PrimaryKey)
    END
END
/**********************************************************
* SQL Statement
*
* Dynamic version of the previous script.
* the Number CTE is created first.
***********************************************************/
SELECT @SQL = '
' + CASE @NOLOCK WHEN 1 
      THEN 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
'
ELSE ''
END
SELECT @SQL += '
;
WITH NUMBERS_CTE AS (
    SELECT 0 AS N
        UNION ALL
    SELECT N + 1000
    FROM NUMBERS_CTE
    WHERE N < 2000000
)
,MIN_MAX_CTE AS (
    SELECT
        N            MinNumber
        ,N + 1000    MaxNumber
    FROM NUMBERS_CTE
)
'
/* 
* Static columns are specified, then the primary key columns
* Then the masked columns are added as the MIN and MAX
* from the subsequent JOIN to the numbers table.
*/
SELECT @SQL += '
SELECT
    ' + '''' + @ServerName + '''' + ' SERVER_NAME
    ,' + '''' + DB_NAME() + '''' + ' DATABASE_NAME
    ,' + '''' + @SchemaName + '''' + ' SCHEMA_NAME
    ,' + '''' + @TableName + '''' + ' TABLE_NAME'
SELECT @SQL += '
    ,MC.' + ColumnName
FROM @PrimaryKeys
SELECT @SQL += '
    ,' + ColumnName
FROM @Columns
/* 
* Each masked column is added to the SELECT list
* as a MIN and MAX
*/
SELECT @SQL +=
    '
    ,' + ColumnName + '_N.MinNumber            ' + ColumnName + '_MIN
    ,' + ColumnName + '_N.MaxNumber            ' + ColumnName + '_MAX'
FROM @Columns
SELECT @SQL += '
FROM [' + @SchemaName + '].[' + @TableName + '] MC WITH (NOLOCK)'
/*
* Add a JOIN statement for each masked column. This determines the MIN / MAX for the column.
* This JOIN is referenced in the column list above.
*/
SELECT @SQL +=
'
    LEFT JOIN MIN_MAX_CTE ' + ColumnName + '_N' + '
        ON MC.' + ColumnName + ' BETWEEN ' + ColumnName + '_N' + '.MinNumber AND ' + ColumnName + '_N' + '.MaxNumber '
FROM @Columns
SELECT @SQL += '
ORDER BY'
/* Order by the PK columns */
SELECT @SQL += 
    CASE RowNumber
        WHEN 1 THEN '
    MC.' + ColumnName 
        ELSE '
    ,MC.' + ColumnName
    END
FROM @PrimaryKeys
SELECT @SQL += '
OPTION(MAXRECURSION 0)
'
BEGIN TRY
    IF @EXECUTE = 1
    BEGIN
        --EXEC(@strSELECTFinal)
        EXEC(@SQL)
    END
    --ELSE SELECT @strSELECTFinal
    ELSE SELECT @SQL
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
NO_EXECUTE:
REVERT;

This shows how masked columns are automatically added to the output and put into histogram buckets with a range of 1000.

Finding text ranges automatically

Show number and text script together, using CONVERT on all masked columns

USE WideWorldImporters
GO
SET NOCOUNT ON
GO
EXECUTE AS USER = 'MaskedReader'
GO
/*******************************************************
* Declare and set the variables for this run *******************************************************/
DECLARE
    @ServerName  varchar(255)  = 'localhost' --@@SERVERNAME
    ,@SchemaName  varchar(255) = 'Purchasing'
    ,@TableName    varchar(255) = 'SupplierTransactions'
        --'SuppliersTest' --'SupplierTransactions'
    ,@PrimaryKey  varchar(255) = NULL  --'SupplierName'
    ,@EXECUTE    tinyint    = 1  -- 1 = execute, 0 = print
    ,@NOLOCK    tinyint    = 1  
         --1 = WITH(NOLOCK), 0 = default lock (committed)
    --,@strStandardFlag  varchar(20)
    --,@strStandardCode  varchar(20)
    ,@SHOW_COLUMNS_ONLY  bit = 0
       --1 = columns only and exit, 0 = don't show column list
    ,@Exclude    varchar(500)
          --= 'BankAccountBranch,BankAccountCode' 
          --CSV list of columns that will be ignored
/*********************************************************
* Temporary table definitions
*********************************************************/
DECLARE @Columns TABLE (
    ColumnID    int
    ,ColumnName    varchar(255)
)
/********************************************************
* Variables set internally
********************************************************/
DECLARE
    @HasText    tinyint
    ,@SQL        varchar(max)
    ,@OrderList    varchar(max)
/*******************************************************
* Set the columns to include
*
* Find masked columns in the table specified.
* Add them to the @Columns table variable
* Note that in the matching section of the script, all values
* are treated as varchar(40), including numeric columns.
********************************************************/
INSERT INTO @Columns
EXEC (
    'SELECT 
        SC.column_id
        ,SC.name
    FROM sys.objects SO
        INNER JOIN sys.columns SC
            ON so.object_id = sc.object_id
        INNER JOIN sys.schemas SS
            ON so.schema_id = ss.schema_id
        INNER JOIN sys.types ST
            ON SC.system_type_id  = ST.system_type_id
            AND SC.user_type_id   = ST.user_type_id
        LEFT JOIN string_split(' + '''' + @Exclude 
            + '''' + ',' + '''' + ',' + '''' + ') SSTR
            ON SC.name COLLATE SQL_Latin1_General_CP1_CI_AS             
             = SSTR.value COLLATE SQL_Latin1_General_CP1_CI_AS 
    WHERE so.name COLLATE SQL_Latin1_General_CP1_CI_AS = ' 
               + '''' + @TableName + '''' 
               + ' COLLATE SQL_Latin1_General_CP1_CI_AS 
        AND ss.name COLLATE SQL_Latin1_General_CP1_CI_AS = ' 
               + '''' + @SchemaName + '''' 
               + ' COLLATE SQL_Latin1_General_CP1_CI_AS 
        AND ST.system_type_id NOT IN (240)
        AND SC.is_masked                = 1
        AND SSTR.value    IS NULL
    ORDER BY sc.name'
);
IF @SHOW_COLUMNS_ONLY = 1
BEGIN
    SELECT * FROM @Columns
    GOTO NO_EXECUTE;
END;
IF (SELECT COUNT(*) FROM @Columns) = 0
BEGIN
    RAISERROR('No columns present: Check that you are running the script from the correct database, that the name of the table is correct and that you have permission to select from the table.',5,1)
    GOTO NO_EXECUTE;
END;
/****************************************************
* Primary Key Columns
*
* The sample script requires a primary key column 
* for it to work  automatically. The primary key columns 
* for the table specified are dynamically inserted into 
* @PrimaryKeys using system tables.
*****************************************************/
DECLARE @PrimaryKeys TABLE (
    PrimaryKeyName   sysname
    ,ColumnName  sysname
    ,RowNumber  int identity
);
INSERT INTO @PrimaryKeys (
    PrimaryKeyName
    ,ColumnName
)
EXEC('
SELECT
    si.name    PrimaryKeyName
    ,sc.name    ColumnName
FROM sys.objects so
    INNER JOIN sys.schemas ss
        ON so.schema_id = ss.schema_id
    INNER JOIN sys.indexes si
        ON so.object_id = si.object_id
    INNER JOIN sys.index_columns ic
        ON so.object_id = ic.object_id
        AND si.index_id    = ic.index_id
    INNER JOIN sys.columns sc
        ON ic.object_id = sc.object_id
        AND ic.index_column_id = sc.column_id
WHERE so.name COLLATE SQL_Latin1_General_CP1_CI_AS = ' 
       + '''' + @TableName + '''' 
       + ' COLLATE SQL_Latin1_General_CP1_CI_AS
        AND ss.name COLLATE SQL_Latin1_General_CP1_CI_AS = ' 
       + '''' + @SchemaName + '''' 
       + ' COLLATE SQL_Latin1_General_CP1_CI_AS
        AND SI.is_primary_key = 1
ORDER BY 
    sc.column_id
')
IF (SELECT COUNT(*) FROM @PrimaryKeys) = 0
BEGIN
    IF @PrimaryKey IS NULL GOTO NO_EXECUTE
    ELSE
    BEGIN
        INSERT INTO @PrimaryKeys (PrimaryKeyName,ColumnName)
        VALUES (@PrimaryKey,@PrimaryKey);
    END;
END
/*****************************************************
* SQL Statement
*
* Dynamic version of the previous script.
* the Number CTE is created first
*****************************************************/
SELECT @SQL = '
' + CASE @NOLOCK WHEN 1 THEN 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
'
ELSE ''
END
SELECT @SQL += '
;
WITH NUMBERS_CTE AS (
    SELECT 1 AS N
        ,CHAR(1) AS CharN
        UNION ALL
    SELECT N + 1
        ,CHAR(N+1)
    FROM NUMBERS_CTE
    WHERE N < 255
)
,CHAR_CTE AS (
    SELECT
        N1.CharN + N2.CharN CharN
    FROM NUMBERS_CTE N1
        CROSS JOIN NUMBERS_CTE N2
)
'
/* 
* Static columns are specified, then the primary key columns
* Then the masked columns are matched to the CHAR CTE
* for partial unmasking
*/
SELECT @SQL += '
SELECT
    ' + '''' + @ServerName + '''' + ' SERVER_NAME
    ,' + '''' + DB_NAME() + '''' + ' DATABASE_NAME
    ,' + '''' + @SchemaName + '''' + ' SCHEMA_NAME
    ,' + '''' + @TableName + '''' + ' TABLE_NAME'
SELECT @SQL += '
    ,MC.' + ColumnName
FROM @PrimaryKeys
SELECT @SQL += '
    ,' + ColumnName
FROM @Columns
SELECT @SQL +=
    '
    ,' + ColumnName + '_N.CharN    ' + ColumnName + '_Start'
FROM @Columns
SELECT @SQL += '
FROM [' + @SchemaName + '].[' + @TableName + '] MC WITH (NOLOCK)'
SELECT @SQL +=
'
    LEFT JOIN CHAR_CTE ' + ColumnName + '_N' 
    + ' ON SUBSTRING(CONVERT(varchar(40),MC.' 
    + ColumnName + '),1,2) 
           COLLATE SQL_Latin1_General_CP1_CS_AS    = ' 
    + ColumnName 
    + '_N.CharN COLLATE SQL_Latin1_General_CP1_CS_AS'
FROM @Columns
SELECT @SQL += '
ORDER BY'
SELECT @SQL += 
    CASE RowNumber
        WHEN 1 THEN '
    MC.' + ColumnName 
        ELSE '
    ,MC.' + ColumnName
    END
FROM @PrimaryKeys
SELECT @SQL += '
OPTION(MAXRECURSION 0)
'
BEGIN TRY
    IF @EXECUTE = 1
    BEGIN
        EXEC(@SQL)
    END
    ELSE SELECT @SQL
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
NO_EXECUTE:
GO
REVERT;
GO

Masked columns are included in the output. All column types are treated as text and have been converted in the SQL, then the start of the column is matched using substring statements.

 

Complete unmasking of larger values

The next challenge is exposing the complete contents of a column. This can be a daunting task that takes quite a long time.

The first, obvious choice might be to brute force a comparison. A rainbow table solution. A rainbow table works by creating a table with all possible values. The masked column is then compared against the fully populated rainbow table using a standard join. This is a parent / child relationship as used everywhere in SQL databases. For small numbers, this is a great strategy due to speed of setup and execution time for the query.

This method has limitations since you need to match the entire number, including the scale if it is a decimal or money column. A standard numbers table works well for matching integers if the target values are within your numbers table. The number column is joined to the masked column in the target table. Complete unmasking in this limited scenario is simple and fast. The previous two examples have versions of numbers tables and a similar technique can be used to uncover small columns if a physical numbers table is not available and you can’t create a new table.

USE WideWorldImporters;
GO
SET NOCOUNT ON;
GO
/*
* Example showing how integer data can be unmasked by
* matching directly to a numbers table.
*
* This only matches to whole numbers.
* All rows could be matched by converting the 
* transaction ammount to an int. This is shown below
* but commented out.
*/
EXECUTE AS USER = 'MaskedReader';
GO
WITH NUMBERS_CTE AS (
    SELECT 0 AS Number
        UNION ALL
    SELECT Number + 1
    FROM NUMBERS_CTE
    WHERE Number < 1000000
)
SELECT
    SupplierTransactionID
    ,SupplierID
    ,TransactionAmount
    ,N.Number
FROM Purchasing.SupplierTransactions ST
    LEFT JOIN NUMBERS_CTE N
        ON ST.TransactionAmount        = N.Number
        --ON CONVERT(int,ST.TransactionAmount)    = N.Number 
           --Example showing converstion to an INT for 
           --additional matches
WHERE TransactionAmount IS NOT NULL
    AND N.Number IS NOT NULL
ORDER BY SupplierTransactionID
OPTION (MAXRECURSION 0);
GO
REVERT
GO

Output showing the query output. Decimals with a scale equal to zero return. The sample script also shows the potential match that would catch many more numbers by converting all TransactionAmount to integers.

 

 

The above solution works for integers and also works on decimal columns where the scale is zero due to the implicit conversion of decimal to integer in the query plan. It could be expanded to include decimals of a specific scale as well. As the solution is expanded and numbers are added it will take longer to match rows, the numbers table will be larger, and your investigations will be more obvious. The query also shows that columns that don’t match, likely due to a scale other than zero or an out-of-range number, don’t join and are returned as NULL.

USE WideWorldImporters
GO
SET NOCOUNT ON
GO
/*
* Example showing how decimal data can be unmasked by
* matching directly to a numbers table.
*
* This matches to decimals.
* All rows could be matched by increasing the range
* but the numbers table is kept small for demonstration
* purposes.
*/
EXECUTE AS USER = 'MaskedReader'
GO
;
WITH NUMBERS_CTE AS (
    SELECT 0 AS Number
        UNION ALL
    SELECT Number + 1
    FROM NUMBERS_CTE
    WHERE Number < 1000000
)
,DECIMAL_CTE AS (
    SELECT
        Number * .01 Number
    FROM NUMBERS_CTE
)
SELECT
    SupplierTransactionID
    ,SupplierID
    ,TransactionAmount
    ,N.Number
FROM Purchasing.SupplierTransactions ST
    LEFT JOIN DECIMAL_CTE N
        ON ST.TransactionAmount = N.Number
WHERE N.Number IS NOT NULL
ORDER BY SupplierTransactionID
OPTION (MAXRECURSION 0)
GO
REVERT
GO

Output shows unmasked decimals with a known scale.

There are a few clear ways to unmask decimals with a specific scale. The numbers table can be built out with all possible decimal values, the masked column can be converted to an integer first and then compared to the numbers table, or the value from the numbers table can be multiplied by a tenth, hundredth or thousandth to match the scale of the masked column.

Creating a full numbers table with all the possible decimal values can take significantly longer to create, takes more disk or memory space, and will make the overall process longer. The actual time will vary depending on the numbers generated.

Converting the masked column to an integer for the comparison in the join is a non-sargable operation and will result in an index scan at the least and possibly a table scan. Excluding the required scan for the conversion, this is a fast operation and easy to implement.

The method I used for the demonstration is using a standard numbers table and multiplying the results by .01 to get decimals to the hundredths position. It is an effective technique for finding an exact match for decimal columns with a minor performance cost, but the precision is limited based on the size of the integers in your numbers table. For most applications, knowing the least significant digits of a decimal doesn’t add value from the perspective of a bad actor. If someone is trying to unmask the value of a current balance in a bank account, they won’t care if the balance is 1000.01 or 1000.99, 1000 is probably close enough.

 The above queries are pure brute-force methods for unmasking columns. The same thing can be done with strings by adding all possible characters to the comparison set. Numbers are faster to unmask due to the limited character set to be traversed and the smaller size of the rainbow table needed to perform the unmasking. Character unmasking using this technique is limited and has a much higher performance cost. It quickly becomes unwieldy and unusable, which is desirable from a security perspective.

 

Specialized scripts for known data formats

Some specialized formats can be unmasked very quickly. This is similar to old NTLMv2 password attacks that broke the password hash into 2 sections. If the format of the column is fixed length with multiple sections, each section can be attacked individually, greatly decreasing the potential time to unmask.

An IP address is a single 32 bit number, but it is represented as 4 bytes. Each of those bytes are generally represented as 0-255 with some exceptions. It would take longer to code for the exceptions instead of just leaving them in the solution. Any invalid combinations will just naturally be excluded when they aren’t matched during the unmasking process.

In the next blog, I will continue along this path and show how you can look for data in specific formats, along with how to just do a brute force search through unknown data.

The post Unmasking SQL Server Dynamic Data Masking, Part 3, Security Concerns appeared first on Simple Talk.



from Simple Talk https://ift.tt/bCypftH
via

Monday, June 12, 2023

Manipulating Data In PostgreSQL: Learning PostgreSQL with Grant

So far in the series I’ve shown how to create databases, tables, constraints, indexes and schema. Now, it’s time to put some of that information to work and begin the process of manipulating data within the database. After all, a database is only useful if there’s information stored within. PostgreSQL makes use of standard SQL for operations like INSERT, UPDATE and DELETE. However, as with so much of what I’ve learned in PostgreSQL, there are quite a few interesting wrinkles that are different to my “SQL Server” eyeballs.

In the sample database I’ve created as a part of this ongoing series, I created a couple of schemas and organized my tables within them. If you wish to execute the code or look at the data structures, the code is in my ScaryDBA/LearningPostgreSQL repository here. The objects and database you will need can be created/reset using the CreateDatabase.sql script, then adding sample data using the SampleData.sql script. The rest of the code from this article is in the  09_DataManipulation folder.

INSERT

We may as well start by adding data to a table. The core behavior of INSERT is very much as you would expect coming from a SQL Server background:

INSERT
        INTO
        radio.radios
(radio_name,
        manufacturer_id,
        connectortype_id,
        digitalmode_id)
VALUES
('GD-88',
7,
3,
2);

The basic behavior is pretty straightforward. You define the statement: INSERT INTO (Note, INTO is not optional in PostgreSQL.). Then you tell it which table you’re addressing, including the schema: radio.radios. Yeah, like SQL Server you can leave the schema off and the PostgreSQL engine will figure things out for you. Don’t do that. It’s a good practice, from the get-go, to define your tables including their schema. You avoid issues down the line by developing that habit early.

Then you list the columns. Like how SQL Server code (and most RDBMS code) works, you can skip columns that have a default (or allow NULL values). In this case, there is a radio_id column that’s a sequence, so I don’t have to supply it in the column list. Then, you define the VALUES as shown. The VALUES clause is where you specify the values that will be set for the column when the row is inserted.

If you wanted to add multiple rows at once, it’s very similar syntax to what you’d see in SQL Server.

INSERT
INTO
radio.radios
(radio_name,
manufacturer_id,
connectortype_id,
digitalmode_id)
VALUES
('FT300DR',
1,
4,
1),

--added a second row
('IC-V86',
2,
2,
NULL);

I simply added a comma delimited set of parentheses to the VALUES. You can also see how I dealt with a NULL value by simply using the defined key word.

As with SQL Server, you can also do an INSERT statement with the source of rows based on a SELECT:

INSERT
INTO
radio.radiobands 
(radio_id,
band_id)
SELECT
9,
band_id
FROM
radio.radiobands
WHERE
radio_id = 2;

In this case, the radio I added earlier has the same two bands as another radio, so I can use the values from that known radio to add to the radio.radiobands table.

Finally, you can use the default value that is defined for a column (or for a column that accepts NULL), by using the key word DEFAULT:

INSERT
INTO
radio.connectortypes (connectorytype_id,
connectortype_name)
VALUES
(DEFAULT,
'F-Type Male');

In this case, since connectortype_id is managed by the identity property, we automatically get a value, so using DEFAULT let’s us still list the column, but we don’t have to supply a value (and in this case, we couldn’t anyway).

If there are default values for all the columns, you could write the INSERT like this:

INSERT
INTO radio.connectorytypes
DEFAULT VALUES;

Although, on this database, that will cause an error since there is no default value defined for the connectorytype_name.

Overall, this behavior is exactly what I would have expected. In fact, it’s largely the same as what I’m used to in SQL Server. There are some differences though.

One small difference is that the INTO keyword, has to be a part of the syntax. Whereas, you can cheat and leave that off in SQL Server. Personally, I tend to use it because that’s how I learned to use T-SQL and I think the INTO adds clarity. PostgreSQL enforces its use because that is part of the ANSI standard, which PostgreSQL follows more closely than most other database systems.

Another useful feature that is not a part of SQL Server is the ability to use OVERRIDING to add your own data rather than let the system generate it for you.

For example, if wanted to specify an identity value for a column, rather than let the identity mechanism generate it for me, I could do this:

INSERT INTO
radio.bands
(band_id,
band_name,
frequency_start_khz,
frequency_end_khz,
country_id)

OVERRIDING SYSTEM VALUE

VALUES (10,
'6 Meters',
50000,
54000,
1);

The OVERRIDING SYSTEM VALUE clause lets me add my own value to the band_id column, bypassing the identity property for that column. That can’t be done within the INSERT statement in T-SQL but instead requires changing a setting prior to running the INSERT. This is clearly a lot easier.

Finally, there’s one really neat trick that you can’t do in SQL Server, ON CONFLICT:

INSERT
INTO
radio.antenna 
(antenna_name,
manufacturer_id,
connectortype_id)
VALUES ('rubber duck',
2,
2)

ON
CONFLICT (antenna_name,
manufacturer_id)
DO
UPDATE
SET
connectortype_id = excluded.connectortype_id;

Basically, this code will add the defined antenna, or it will update an existing antenna, but only for the row where we violated the unique index that exists on the table on the two columns, antenna_name and manufacturer_id. In short, it’s a way to do a MERGE statement without doing a MERGE statement. I’m not sure if, like MERGE in SQL Server, there are performance implications. You can also use the clause DO NOTHING to prevent a response to the conflict.

This is most of the syntax for the INSERT statement, but not everything. If you want to see more, you can see there are a few additional features here in the PostgreSQL INSERT statement documentation.

UPDATE

When it’s time to change data in the database, you’re going to use the UPDATE statement, as you’d expect:

UPDATE
radio.bands
SET
band_name = '70 CM'
WHERE
band_id = 2;

The statement is UPDATE. You then supply the table, and yes, just as you can only add data to a single table at a time, you can only modify data to a single table at a time. The SET command then lets you pick and choose which columns you’re going to modify. Finally, the WHERE clause is used to filter the data to only modify the row or rows, you’re interested in.

Leaving off the WHERE clause will modify all data in the table.

You can also use the FROM clause to modify data between tables something like this:

UPDATE
radio.bands
SET
band_name = r.radio_name
FROM
radio.radios AS r
WHERE
band_id = r.radio_id;

One additional note on UPDATE. Since it’s possible to use table inheritance within PostgreSQL, an additional clause can be added to UPDATE statements to ensure that only the table specified has data modified within it. (A discussion about table inheritance is beyond this article, but the PostgreSQL documentation has a straightforward explanation here):

UPDATE ONLY
radio.bands
SET
band_name = r.radio_name
FROM
radio.radios AS r
WHERE
band_id = r.radio_id;

Except for the addition of the ONLY clause, this UPDATE is the same as the one above. However, now, if radio.bands was inherited from another table, this statement ensures that only the specific table specified is affected.

DELETE

With the DELETE command, we finally have a bit more deviation from the standards, although, the standards are there as well. A simple statement like this will remove all data in a table:

DELETE
FROM
radio.bands;

Just as with SQL Server, you can also use the TRUNCATE command to remove data from a table and it is faster. TRUNCATE does have limitations (permission and will not work with FOREIGN KEY constraints), for example. In fact, if you attempt to execute this DELETE statement you will get an error because it causes a foreign key constraint error.

It does have benefits for larger updates such as removing all row versions without the VACUUM process needing to execute (For more details on the VACCUM process, check out Henrietta Dombrovskaya’s post here).

If you want to get specific, you take advantage of the WHERE clause:

DELETE
FROM
radio.antenna
WHERE
antenna_id = 42;

That’s about what I’d expect. One point, just as you had to keep the INTO clause for an INSERT, you must use the FROM keyword in DELETE. And if you want to reference another table, you don’t simply start writing JOIN statements as I would in T-SQL. Instead, you must insert the USING clause:

DELETE
FROM
radio.antennabands AS ab
USING radio.bands AS b
WHERE
ab.band_id = b.band_id
AND b.band_name = '6 Meters';

So here I used an alias on both the antennabands table and the bands table. Then I used the WHERE clause to define the join criteria between the tables, and the filtering criteria for the band_name.

In addition to these behaviors, you also have the ONLY clause to deal with inheritance.

The RETURNING Clause

One piece of behavior that’s common across all the standard data manipulation commands is the RETURNING clause. Basically, this returns as a result set, the data that was created or modified. So, in the example of an INSERT, you wouldn’t see anything other than what you supplied, except where there are defaults such as a sequence number on an identity column. Then, you can get the value, or values for multi-row inserts, that were generated.

For an UPDATE statement, the RETURNING clause will return the new values for the row, especially useful if you’ve done calculations on a column or columns to see the values that resulted.

When you run a DELETE statement, the RETURNING clause will show you the values for the row or rows that were removed from the table.

The RETURNING clause can be put to really interesting types of use, especially since you can use common table expressions (CTEs) with all these data manipulation queries. That makes it possible to do something like this:

WITH addant AS
(
/* create a new antenna row */
INSERT
INTO
radio.antenna (antenna_name,
manufacturer_id,
connectortype_id)
VALUES('Rubber duck',
1,
2)
RETURNING antenna_id)
/*
take the new antenna_id and create
a new antennabands row 
*/
INSERT
INTO
radio.antennabands 
(antenna_id,
band_id)
SELECT
aa.antenna_id,
1
FROM
addant AS aa;

The WITH clause defines a rowset, addant, which is just the RETURNING value of the antenna_id generated from the INSERT statement that defines the CTE. I can then use that value to add another row to another table, all as part of a single statement. This opens up a lot of possibilities of stacking statement that can run as one single statement.

MERGE

As in SQL Server, the MERGE command gives you the ability to combine INSERT, UPDATE and DELETE operations in various combinations into a single statement. When using MERGE, you are going to be evaluating conditions to determine behaviors. This means you’ll always have a target table where the actions are going to occur. In addition, you need to have an evaluation data source. This can be a table, or a set of tables defined in a sub-select, whatever you need to evaluate the necessary actions.

From there, you can define WHEN MATCHED for conditions that require a matched value, or WHEN NOT MATCHED for those other conditions. The order you define them in, is the order in which they’ll be evaluated.

Worth noting, the MERGE command is new to PostgreSQL 15.

Here’s an example. I’ll build out some data in a temporary table, and then use the logic to add the data, update it, or delete it, based on information being passed:

CREATE TEMPORARY TABLE radioupdates (radio_name varchar(100),
manufacturer_id int,
connectortype_id int,
delete_flag int);
INSERT
INTO
radioupdates (radio_name,
manufacturer_id,
connectortype_id,
delete_flag)
VALUES
('UV5R',
2,
3,
0),
('UV5R',
3,
3,
0),
('UV5R',
1,
3,
1);

Then I will use the following MERGE statement to merge the values in the temp table into the radios table

MERGE
INTO
radio.radios AS r
USING radioupdates AS ru
ON
ru.radio_name = r.radio_name
AND ru.manufacturer_id = r.manufacturer_id
WHEN NOT MATCHED THEN
INSERT
VALUES(DEFAULT,
ru.radio_name,
ru.manufacturer_id,
NULL,
ru.connectortype_id,
NULL)
WHEN MATCHED
AND ru.delete_flag = 0 THEN
UPDATE
SET
connectortype_id = ru.connectortype_id
WHEN MATCHED
AND ru.delete_flag = 1 THEN
DELETE;

The trick is just to get the logic right. In my MERGE statement, the logic is: if there are no matches based on the ON criteria, WHEN NOT MATCHED, I’ll INSERT the row. Then, if it matches, but it’s not flagged to be a DELETE, it does an UPDATE operation on the values from the source. Otherwise, if it matches and it’s flagged for deleting, it gets deleted.

You can also specify DO NOTHING for the outcome of evaluations. The ONLY key word can be used to deal with inheritance as mentioned in the UPDATE section. You can even use OVERRIDING in the INSERT clause. In short, most of the behaviors we’ve gone over through this article are available in MERGE.

Just remember, the old approach was to just use the ON CONFLICT clause to achieve an UPSERT (UPDATE or INSERT) command. That method was not as powerful as MERGE when you need the extra complexity, for example, removing data from the target.

For complete details about the MERGE statement, here is the link to the PostgreSQL documentation.

Conclusion

Manipulating data within PostgreSQL is one of the easiest things I’ve learned so far. Mostly, broad strokes, it’s the same as with SQL Server. While there are a few details different in some areas, mostly, this is the kind of behavior I expected. I really like how you can use common table expressions with these commands. I also like how RETURNING works to allow you to do some really customized behaviors. Overall, there’s quite a bit of useful functionality within PostgreSQL when it comes to directly manipulating data.

 

The post Manipulating Data In PostgreSQL: Learning PostgreSQL with Grant appeared first on Simple Talk.



from Simple Talk https://ift.tt/P0R3xry
via

Friday, June 9, 2023

A Guide to INSERT, UPDATE, and DELETE Statements in Oracle

In this article, we’ll be focusing on three of the most used SQL commands in Oracle: INSERT, UPDATE, and DELETE. These commands are used to insert new data into tables, update existing data, and delete data from tables, respectively.

In this article I will take a closer look at each of these statements and how they are used in Oracle. Please note the INSERT, UPDATE, and DELETE statements can only be used on tables that you have been granted the privilege to execute these commands.

Note that by default, Oracle implicitly starts a transaction after every statement. Because of this, you must use the COMMIT or ROLLBACK statements to manage these transactions after you attempt to make your changes to the contents of a table (the transaction starts even if no data is modified, like if you have a WHERE clause that does not return FALSE for any rows.) For more detail on Oracle transactions, see Transactions in the Oracle documentation)

A transaction is a sequence of one or more SQL statements that are treated as a single unit of work. Once you have made your changes, you need to execute one of the following statements:

  • COMMIT: This statement is used to permanently save the changes made during a transaction. When you issue a COMMIT statement, all the changes made during the transaction are made permanent and cannot be undone. After the COMMIT statement is executed, a new transaction begins.
  • ROLLBACK: This statement is used to undo the changes made during a transaction. When you issue a ROLLBACK statement, all the changes made during the transaction are undone, and the database is restored to its previous state. After the ROLLBACK statement is executed, a new transaction begins.

It’s important to use COMMIT and ROLLBACK statements carefully to ensure data integrity. If a transaction is not committed, the changes made during the transaction will not be visible to other users or applications and could hinder their work. If a transaction is rolled back, any changes made during the transaction will be lost.

Here’s an example of an "Employee" table: You can use the following SQL script to create the "Employee" table. We will use this table to learn to insert, update and delete commands.

Note: In our following CREATE TABLE Statement, we utilized the Oracle NOT NULL constraint for Name, LastName, and Dob columns, which ensures that a column cannot store NULL values. These constraints are inline and commonly included in the column definition of a CREATE TABLE statement. When you define one or more columns as the primary key for a table, it automatically includes the NOT NULL constraint, which prohibits NULL values from being inserted into that column. If you try to insert a NULL value into a primary key column, or one defined as NOT NULL, Oracle SQL will raise an error.

Additionally in Oracle SQL, a default constraint sets a value that is automatically assigned to a column when a new row is inserted into a table and a value for that column is not specified. The default value is specified when the table is created using the DEFAULT keyword. we have defined the DEFAULT value 'Unknown' for the "Department" column.

SQL script to create the "Employee" table.

CREATE TABLE Employee (
    EmployeeId INT PRIMARY KEY,
    Name VARCHAR(50) NOT NULL,
    LastName VARCHAR(50) NOT NULL,
    FirstName VARCHAR(50) NOT NULL,
    Department VARCHAR(50) DEFAULT 'Unknown',
    Dob DATE NOT NULL,
    Salary DECIMAL(10, 2) NOT NULL 
);

The INSERT Statement

In this section I will cover the typical uses of the INSERT statement. The Oracle INSERT statement is very similar to other RDBMS platforms, but it also has several, quite useful differences.

INSERT Statement Basic Syntax:

The SQL INSERT statement is used to add new data to a database. There are different types of SQL INSERT statements, each with its syntax and usage. The basic INSERT statement is used to insert a single row of data into a table, while the other types are used for more complex data insertion operations.

The basic INSERT command is used to add new data to a table in Oracle. The syntax for this command is as follows:

INSERT INTO table_name (column1, column2, ..., columnN)
VALUES (value1, value2, ..., valueN);

In this syntax, table_name is the name of the table you want to insert data into, and column1 through columnN are the names of the columns you want to insert data into. The VALUES keyword is followed by a comma-separated list of values that correspond to the columns you specified earlier.

In this section, we will cover the following different ways of writing SQL INSERT statements.

  • Single row INSERT statement.
  • INSERT ALL statements.
  • INSERT from SELECT statement.

Single row INSERT statement

A single-row INSERT statement inserts a single row into a table. Let’s consider an example to understand this statement better. Using the table named "Employee" as defined at the beginning of the article, to insert a new employee row into this table, you can use the following INSERT statement:

INSERT INTO Employee (EmployeeId, Name, LastName, FirstName,
      Department, Dob, Salary)
VALUES ('1000', 'Allen Cox', 'Cox', 'Allen', 'IT', 
      TO_DATE('01-July-1982', 'DD-MM-YYYY'),75000);
COMMIT;

This statement will add a new row to the "Employee" table with the specified values.

Now let’s see what happens if we don’t specify the "Department" column in our INSERT statement because we already defined a default value for the "Department" column in the CREATE TABLE statement.

INSERT INTO Employee (EmployeeId, Name, LastName, FirstName,
      Dob, Salary)
VALUES ('1001', 'Allen Cox', 'Cox', 'Allen',  
     TO_DATE('01-July-1982', 'DD-MM-YYYY'),75000); 

COMMIT;

You will notice that the "Department" column has the default value 'Unknown', which is automatically assigned because we omitted the column from the INSERT statement.

Output:

C:\Users\CRAWAT\AppData\Local\Temp\SNAGHTML6bcd14e7.PNG

Note: It is not required to specify the columns in the INSERT statement. So, the following is allowed:

INSERT INTO Employee 
VALUES ('1001', 'Allen Cox', 'Cox', 'Allen',  
     TO_DATE('01-July-1982', 'DD-MM-YYYY'),75000); 

COMMIT;

This will be covered later in the article in more detail, but you should always specify the columns for the INSERT statement in code that is meant to be executed sometime in the future. The time savings of not including the list of columns is so much less than when there are changes to the underlying table and the code breaks and must be supported.

Inserting Multiple Rows at a time

In this section, I will cover the multiple ways that you can insert more than a single row at a time.

Multiple Batches

Perhaps this is obvious, but one straightforward way is to insert more than a few rows, is to create a script with multiple inserts in a batch. The script above will put five records into the Employee table.

INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, 
                      Department, Dob, Salary)
VALUES ('1002', 'Dave Carry', 'Carry',  'Dave', 'Sales', 
       TO_DATE('01-Jan-1992', 'DD-MM-YYYY'),70000);

INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, 
                      Department, Dob, Salary)
VALUES ('1003', 'Amit Singh','Singh',   'Amit', 'Sales', 
       TO_DATE('20-Oct-1991', 'DD-MM-YYYY'),50000);

INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, 
                      Department, Dob, Salary) 
VALUES ('1004', 'Rhonda Grant', 'Grant',        'Rhonda', 
       'Marketing', 
       TO_DATE('15-May-1980', 'DD-MM-YYYY'),60000);

INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, 
                      Department, Dob, Salary) 
VALUES ('1005', 'Marvin Cox', 'Cox',    'Marvin', 'Marketing', 
       TO_DATE('15-Jan-1985', 'DD-MM-YYYY'),62000);

INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, 
                      Department, Dob, Salary) 
VALUES ('1006', 'Dave Grant', 'Grant',  'Dave', 'Sales', 
        TO_DATE('05-Oct-1980', 'DD-MM-YYYY'),90000);

COMMIT;

Rerun the SELECT statement using the "Employee" table now looks like this:

Graphical user interface, table Description automatically generated

If there are errors in any of the rows, you can ROLLBACK the transaction and none of the new rows would be created.

INSERT ALL statement

The INSERT ALL statement in Oracle allows you to insert multiple rows into one or more tables using a single statement. It is useful when you need to insert data into multiple tables based on a single source of data.

Syntax:

INSERT ALL
    INTO table1 (column1, column2, ...) 
    VALUES (value1, value2, ...)

    INTO table2 (column1, column2, ...) 
    VALUES (value1, value2, ...)

    INTO table3 (column1, column2, ...) 
    VALUES (value1, value2, ...)

Subquery;

In the original statement, it is required that each value expression value1, value2, or value3 refers to a column returned by the select list of the subquery. It is important to note that the column names and values must match in each INTO and VALUES clause. Also, the number of columns and their data types must be compatible between the INTO clause and the corresponding VALUES clause.

However, to use literal values instead of values returned by the subquery, you can utilize the following subquery:

SELECT * FROM dual;

Here’s an example:

Suppose we have two tables: "Employee" and "Address". The "Employee" table is the same as the one we created at the beginning of the article. The "Address" table is as follows:

CREATE TABLE Address (
   EmployeeId NUMBER PRIMARY KEY,
   Address_Line1 VARCHAR2(100),
   Address_Line2 VARCHAR2(100),
   City VARCHAR2(50),
   State VARCHAR2(50),
   Country VARCHAR2(50)
);

Let’s say we want to insert data into both tables using a single INSERT ALL statement. We can do this as follows:

INSERT ALL

  INTO Employee (EmployeeId, Name, LastName, FirstName,
              Department, Dob, Salary)
  VALUES ('1007', 'Ram Singh', 'Singh', 'Ram', 'IT', 
          TO_DATE('08-July-1982', 'DD-MM-YYYY'),75000)
 
  INTO Address (EmployeeId, Address_Line1, City, 
                State, Country) 
  VALUES ('1007', '123 Main St', 'Anytown', 'CA', 'USA')

  SELECT * FROM dual; 

COMMIT;

In this example, we are inserting data into two tables, "Employee" and "Address". The SELECT * FROM dual statement at the end is required because the INSERT ALL statement requires a subquery (in this case a SELECT statement) at the end.

The first INTO clause specifies that we want to insert data into the "Employee" table, and the second INTO clause specifies that we want to insert data into the "Address" table. The SELECT statement at the end specifies the data we want to insert.

After executing this statement, the "Employee" table would contain the following row:

And the "Address" table would contain the following row:

Graphical user interface Description automatically generated with medium confidence

INSERT ALL subquery example

Suppose we have two tables, "Name" and "Salary" and we want to insert records into both tables using a single INSERT ALL statement. We’ll INSERT the employee’s salary and name details from the "Employee" table.

You can create "Name" and "Salary" table using the following code:

CREATE TABLE Name (
  EmployeeId NUMBER PRIMARY KEY,
  LastName VARCHAR(50) NOT NULL,
  FirstName VARCHAR(50) NOT NULL,
  Dob DATE NOT NULL
);

CREATE TABLE Salary (
  EmployeeId NUMBER PRIMARY KEY,
  Salary DECIMAL (10, 2) NOT NULL 
);

Let’s now write an INSERT statement to insert the data.

INSERT ALL

    INTO Name   (EmployeeId, LastName , FirstName , Dob)
         VALUES (EmployeeId, LastName , FirstName , Dob)

    INTO Salary (EmployeeId , Salary)
         VALUES (EmployeeId , Salary)

SELECT EmployeeId, LastName , FirstName , Dob, Salary
FROM Employee ;

The data in the “Name” table appears as shown after executing the INSERT ALL statement mentioned above.

A screenshot of a table Description automatically generated with low confidence

Output of the "Salary" Table:

A screenshot of a table Description automatically generated with low confidence

INSERT from SELECT statement

The INSERT INTO SELECT statement is used to insert data into a table from another table. This can be useful when you need to copy data from one table to another or when you need to modify the data in some way before inserting it into the new table.

The syntax for the INSERT INTO SELECT statement is as follows:

INSERT INTO table_name (column1, column2, ..., columnN) 
SELECT column1, column2, ..., columnN 
FROM source_table 
WHERE condition;

Just like for the single-row usage of the INSERT statement, table_name is the name of the table you want to insert data into, and column1 through columnN are the names of the columns you want to insert data into.

The SELECT keyword is followed by a list of columns from the source table, and the FROM keyword is followed by the name of the source table. The WHERE keyword is optional and allows you to filter the data before inserting it into the new table.

For example, the following SQL statement would copy all rows from the "Employee" table where the "Department" column is "Sales" into a new table called "Sales_Employee".

Use the following SQL to create the "Sales_Employee" table.

CREATE TABLE Sales_Employee (
    EmployeeId  varchar(15) Primary key,
    Name varchar(15),
    Dob DATE,
    Salary NUMBER(8,0)
);

Use the following SQL to insert the data into the "Sales_Employee" table.

INSERT INTO Sales_Employee(EmployeeId, Name, Dob, Salary) 
SELECT EmployeeId, Name, Dob, Salary 
FROM Employee
WHERE Department = 'Sales';

COMMIT;

The SQL statement above will put three records into the "Sales_Employee" table. The output of the SELECT statement from the "Sales_Employee" table looks like this.

Graphical user interface, text, application, table Description automatically generated

Insert Data Without Using an Explicit Column List

This brings us to a discussion of INSERT statements that do not specify a column list. It is a useful technique when doing quick, ad-hoc work, but it has limitations.

In previous examples, we provided values for all columns of the table. This approach allows you to choose only the columns you wish to create data for (and let the NULL and/or default constraints handle the other columns.) If you do not include all columns, you must ensure that the values are in the same order as the columns are declared in the table.

In this case, the INSERT INTO syntax would be as follows:

INSERT INTO table_name
VALUES (value1, value2, value3, ...);

COMMIT;

So for example, you could write the following statement to add rows from “Employee” into the “Sales_Employee” table:

INSERT INTO Sales_Employee 
SELECT EmployeeId, Name, Dob, Salary From Employee
WHERE Department = 'Sales';

COMMIT;

This is a valid way to write an INSERT statement. It is generally a good practice to specify the column list when inserting data into a table in Oracle SQL. By specifying the column list, you explicitly state which columns the data is being inserted into, and in which order.

This can help prevent errors and ensure that the data is inserted into the correct columns. While this may not seem like a big deal, if the structure of the table changes and you execute this statement, the best case is that you receive an error. Worst case data is inserted that makes no sense.

There are several reasons why it is considered good practice to specify the column list:

  • Clarity: By specifying the column list, you make it clear which columns are being populated with data. This can make your code more readable and easier to understand.
  • Maintenance: Specifying the column list can make it easier to maintain your code in the long term. If you or another developer need to modify the code or data structures later, it will be easier to understand and modify if the column list is explicitly stated.
  • Performance: In some cases, not specifying the column list can result in slower performance. If you do not specify the column list, Oracle SQL will have to perform additional work to determine which columns the data should be inserted into. This can result in slower insert times, especially for large datasets.

There are some cases where not specifying the column list may be acceptable. For example, if you are inserting data into a table with a very small number of columns, and the order of the columns is unlikely to change, you may be able to omit the column list without much risk.

In general, it is recommended to always specify the column list when inserting data into a table in Oracle SQL, unless you have a good reason not to.

UPDATE Statement:

The UPDATE statement is used in Oracle SQL for modifying data in a table. It allows you to change the values of one or more columns in one or more rows of a table based on specified conditions.

UPDATE Syntax:

The basic syntax of the UPDATE statement is as follows:

UPDATE table_name 
SET column1 = scalar_expression1, 
    column2 = scalar_expression2,
     ..., 
    columnN = scalar_expression2 
WHERE condition;

In this syntax:

  • table_name is the name of the table you want to update.
  • column_name is the name of the column you want to update.
  • scalar_expression is the expression that calculates the new value for the column. This can be a constant, a function call, a column reference, an arithmetic expression, or a string expression.
  • condition is an optional condition that specifies which rows to update. If omitted, all rows in the table will be updated. Let’s consider an example to understand this statement better.

Examples:

Suppose you want to update the salary of the employee with an “EmployeeId" of 1002 to 80000.

Before executing the UPDATE statement, the data in the "Employee" table looks like the following:

A picture containing text Description automatically generated

You can use the following UPDATE statement.

UPDATE Employee 
SET Salary = 80000 
WHERE EmployeeId = 1002;

COMMIT;

After executing the UPDATE statement, the data in the "Employee" table will look like the following as we can see the Salary column is updated to 80000.

As an example of updating multiple columns, let’s edit “Salary", “Department", and “LastName" column values using a single UPDATE statement. Before executing the UPDATE statement, the data in the "Employee" table looks like the following:

UPDATE Employee 
SET Salary = 70000, 
    Department='Sales',
    LastName='Brown' 
WHERE EmployeeId = 1002;

COMMIT;

After running the UPDATE statement, you would notice that the “Salary", “Department", and “LastName" column values for "EmployeeId" 1002 have been updated to this.

A picture containing timeline Description automatically generated

Now let’s use an arithmetic expression to update the "Salary" column in the "Employee" table:

Before executing the UPDATE statement, the data in the "Employee" table looks like the following:

Table Description automatically generated

Now run the following UPDATE statement:

UPDATE Employee
SET Salary = Salary * 1.1
WHERE department = 'Sales';

COMMIT;

We are using an arithmetic expression to update the salary column of all employees in the Sales department. The SET clause sets the "Salary" column to the current value of salary multiplied by 1.1, effectively giving all sales employees a 10% raise.

Table Description automatically generated with medium confidence

Update using a subquery:

The following statement will update the "Salary" column of all rows in the "Employee" table where the "Department" column equals 'Sales' to the average salary of employees in the Sales department.

UPDATE Employee
SET Salary = (
  SELECT AVG(Salary)
  FROM Employees
  WHERE Department = 'Sales'
)
WHERE Department = 'Sales';

COMMIT;

After running the UPDATE statement, you would notice the following change in the Salary Column of table “Employee”.

Graphical user interface, application, table Description automatically generated

Tips for Using the UPDATE Statement

  1. Pay attention to the WHERE clause: Use the WHERE clause to specify which rows you want to update. This will help to improve performance and prevent accidental updates to the wrong rows. If you omit the WHERE clause, you risk updating all rows in the table.
  2. Keep backups of your data: Be careful when using the UPDATE statement in a production environment. Always make sure you have a backup of your data before performing any modification operations. This can help you recover your data in case of a mistake or error.
  3. Use subqueries carefully: Subqueries can be a powerful tool when working with the UPDATE statement, as they allow you to update data based on the results of another query. However, subqueries can also be slow and resource-intensive, especially if they are used to update a large number of rows. Use subqueries carefully and only when necessary.
  4. Test your UPDATE statement first: Before running an UPDATE statement on a production database, it is important to test it on a smaller dataset to ensure that it is working correctly. This can help you identify any syntax errors or other issues before you make changes to your live data.

DELETE Statement:

The DELETE statement is used to remove one or more rows from a table. The DELETE statement is utilized for managing data in a database, and it is essential to understand how to use it effectively.

DELETE Basic Syntax:

DELETE FROM table_name 
WHERE condition;

In this syntax, ‘table_name’ is the name of the table from which you want to delete rows, and ‘condition’ is an expression that evaluates to true or false for each row in the table. If the condition is true for a row, that row will be deleted.

For example, the following SQL statement would delete all rows from the “Employee” table where the “Department” column is ‘Sales’.

DELETE FROM Employee 
WHERE Department = 'Sales';

COMMIT;

If you want to delete all rows from a table, you can omit the WHERE clause:

DELETE FROM table_name;

This statement will delete all rows from the specified table.

For example, the following SQL statement would delete all rows from the “Employee” table.

DELETE FROM Employee;

COMMIT;

Deleting Data using a subquery

In some cases, you may need to delete rows based on values in another table. Oracle allows you to do this using the DELETE statement with a subquery. The subquery is used to specify which rows to delete from the target table.

The syntax for deleting data from multiple tables using a subquery is as follows:

DELETE FROM table_name1 
WHERE column_name IN (SELECT column_name 
                      FROM table_name2 
                      WHERE condition);

In this syntax, table_name1 is the target table, and table_name2 is the source table. The subquery in parentheses is used to select the rows to delete from the target table based on the specified condition.

For example, the following SQL statement would delete all employees from the “Employee” table whose Salary is greater than 60000 in the "Sales_Employee" table.

DELETE FROM Employee 
WHERE Employeeid IN (SELECT Employeeid 
                     FROM Sales_Employee 
                     WHERE SALARY > 60000);

COMMIT;

Tips for Using the DELETE Statement

  1. Pay attention to the WHERE clause to specify the conditions for deleting rows. If you omit the WHERE clause, you risk deleting all rows in the table. (Which is quite bad if not what you expected to do.)
  2. It’s important to exercise caution when using the DELETE statement to remove a large number of rows in a production environment. Always make sure you have a backup of your data before performing any deletion operations.
  3. Use the TRUNCATE statement instead of DELETE when you need to delete all rows from a table. TRUNCATE is much faster than DELETE for this purpose. (Note that TRUNCATE has limitations and security differences to DELETE, for more detail on TRUNCATE, check out the Oracle documentation here.)

Summary

In this article, we have looked at the usage of SQL commands, INSERT, UPDATE, and DELETE in Oracle, one of the most widely used relational database management systems. The article focuses on the basic syntax and types of SQL INSERT statements in Oracle, including single row and inserts from SELECT statements with examples.

Additionally, it covers the basic syntax of UPDATE and DELETE statements in Oracle. These commands help in manipulating the data in the database efficiently. We learned to add new data, update existing data, and delete data from a table, respectively followed by some tips.

 

The post A Guide to INSERT, UPDATE, and DELETE Statements in Oracle appeared first on Simple Talk.



from Simple Talk https://ift.tt/TLVmfW4
via