Thursday, February 15, 2024

Databricks - How to create function UDF

A user-defined function (UDF) is a means for a user to extend the native capabilities of Apache Spark™ SQL. SQL on Databricks has supported external user-defined functions written in Scala, Java, Python and R programming languages since 1.3.0. While external UDFs are very powerful, they also come with a few caveats:

  • Security. A UDF written in an external language can execute dangerous or even malicious code. This requires tight control over who can create UDF.
  • Performance. UDFs are black boxes to the Catalyst Optimizer. Given Catalyst is not aware of the inner workings of a UDF, it cannot do any work to improve the performance of the UDF within the context of a SQL query.
  • SQL Usability. For a SQL user it can be cumbersome to write UDFs in a host language and then register them in Spark. Also, there is a set of extensions many users may want to make to SQL which are rather simple where developing an external UDF is overkill.

 https://www.databricks.com/blog/2021/10/20/introducing-sql-user-defined-functions.html

Thursday, January 18, 2024

Openai with databricks sql for queries in natural language

Modern data platforms store and collect an incredible amount of both useful data and metadata. However, even knowing the metadata itself might be not useful for the end-users who don’t have enough experience with classical components of a relation-based data model. One of the challenges is not only the ability to write proper SQL statements to select the relevant information but also understanding of what needs to be joined (and how exactly this shall be done) even to get the simplest insights (e.g. top-5 customers from a given region by the number of orders).

 https://polarpersonal.medium.com/using-openai-with-databricks-sql-for-queries-in-natural-language-cf6521e88148

Wednesday, October 18, 2023

Copy CSV file to Databricks Delta table

COPY INTO delta.`abfss://container@storageAccount.dfs.core.windows.net/deltaTables/target`
  FROM (SELECT key, index, textData, 'constant_value'
          FROM 'abfss://container@storageAccount.dfs.core.windows.net/base/path')
  FILEFORMAT = CSV
  PATTERN = 'folder1/file_[a-g].csv'
  FORMAT_OPTIONS('header' = 'true')

-- The example below loads CSV files without headers on ADLS Gen2 using COPY INTO.
-- By casting the data and renaming the columns, you can put the data in the schema you want
COPY INTO delta.`abfss://container@storageAccount.dfs.core.windows.net/deltaTables/target`
  FROM (SELECT _c0::bigint key, _c1::int index, _c2 textData
        FROM 'abfss://container@storageAccount.dfs.core.windows.net/base/path')
  FILEFORMAT = CSV
  PATTERN = 'folder1/file_[a-g].csv'


 https://docs.databricks.com/en/ingestion/copy-into/examples.html


Thursday, August 17, 2023

Databricks Rename Table Column Name

 ALTER TABLE enterprise_db.tblmf_sources SET TBLPROPERTIES (

  'delta.minReaderVersion' = '2',
  'delta.minWriterVersion' = '5',
  'delta.columnMapping.mode' = 'name'
)
Alter table RENAME enterprise_db.tblmf_sources COLUMN     sourceName TO SourceName

Friday, May 26, 2023

Remove and add widgets in databricks dbutils.widgets



Remove:- dbutils.widgets.removeAll()

Add:- dbutils.widgets.text("EnterCaseNo", "17102603374")

Thursday, May 11, 2023

Writing letter using openAI python

This code generated by chat.openai.com and this code is for databricks notebook. I modified according to my need.


 %python

import openai
openai.api_key = os.environ["OPENAI_API_KEY"]

#prompt = "Write a news article about a new breakthrough in cancer research."
#prompt = "Write a letter about cancer research. to a doctor "
#prompt = "Write a letter to supervisor about leave"
prompt =dbutils.widgets.get("SearchBox")

response = openai.Completion.create(
    engine="text-davinci-002",
    prompt=prompt,
    max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5,
)

article = response.choices[0].text
#print(article)

df = spark.createDataFrame([(article,)], ["article"]  )
# Display the DataFrame as a table
display(df)

Tuesday, April 18, 2023

How to see Stored Proc code if you don't have access SQL Server

 EXEC [SERVER NAME].[DATABASE NAME].DBO.SP_HELPTEXT 'Stored Proc Name'


Thursday, April 13, 2023

Databricks SQL Useful Shortcut

 

 Databricks SQL Useful Shortcut

Ctrl+Shift+L : List tables in the current database.

Ctrl+Shift+T : Create a new table.

Ctrl+Shift+D : Drop a table.

Ctrl+Shift+U : Update a table.

Ctrl+Shift+I : Insert a row into a table.

Ctrl+Shift+D : Delete a row from a table.

Ctrl+Shift+F : Filter data in a table.

Ctrl+Shift+S : Sort data in a table.

Ctrl+Shift+P : Perform a SQL query.

Databricks Notebook Useful Shortcut

Databricks notebook shortcut

Ctrl+Enter : Run the current cell.

Shift+Enter : Run the current cell and move to the next cell.

Ctrl+Alt+p : Create a cell above the current cell.

Ctrl+Alt+n : Create a cell below the current cell.

Ctrl+Z : Undo the last action.

Ctrl+Y : Redo the last action.

Ctrl+A : Select all text in the current cell.

Ctrl+C : Copy the selected text.

Ctrl+V : Paste the copied text.

Ctrl+X : Cut the selected text.

Ctrl+L : Show or hide line numbers.

Ctrl+K : Comment out the selected text.

Ctrl+U : Uncomment the selected text.

Ctrl+Shift+F : Format the code in the current cell.

Ctrl+Shift+B : Run all cells in the current notebook.

Ctrl+Shift+S : Save the current notebook.

Ctrl+Shift+G : Go to line number.

Ctrl+Shift+H : Find and replace text.

Ctrl+Shift+P : Open the command palette.

Ctrl+Shift+Q : Quit Databricks.

Alt + Enter: Run the current cell and insert a new one below it

Esc + 0: Restart the kernel

Esc + M: Convert the current cell to a Markdown cell

Esc + Y: Convert the current cell to a code cell

Esc + A: Insert a new cell above the current cell

Esc + B: Insert a new cell below the current cell

Esc + X: Cut the current cell

Esc + C: Copy the current cell

Esc + V: Paste the cell that was cut or copied

Esc + D, D: Delete the current cell


Wednesday, March 22, 2023

ISNULL in Databricks SQL

Use 

 coalesce

coalesce(member_count,0)

Wednesday, March 8, 2023

Command line executable sql server ChatGPT

 A command line executable for SQL Server is a file that can run SQL queries or scripts using a command-line utility such as sqlcmd123. It usually has an extension like .sql or .bat. To run a command line executable for SQL Server, you need to know its file path and use the appropriate syntax for your utility. For example:


In sqlcmd, you can use the -i option to specify the input file name. For example: sqlcmd -S server_name -d database_name -i C:\Scripts\script.sql

In a batch file, you can use the sqlcmd command with the input file name as an argument. For example: sqlcmd -S server_name -d database_name -i C:\Scripts\script.sql

You can also pass other options to the sqlcmd utility, such as -o to specify the output file name, -v to define variables, or -q to execute a query directly. For more information on sqlcmd options, see here.


If you want to create your own command line executable for SQL Server, you can

Tuesday, March 7, 2023

ChatGPT Open AI Excel VBA error

This code is generated by ChatGPT but still getting error to connect to API. help.

Error in this line: request.send JsonConverter.ConvertToJson(body)


 Sub ChatItem()

    'Declare variables

    Dim request As Object

    Dim response As String

    Dim url As String

    Dim headers As Object

    Dim body As Object

    

    'Set url and headers for API call

    url = "https://api.openai.com/v1/engines/chatgpt/completions"

    Set headers = CreateObject("Scripting.Dictionary")

    headers.Add "Authorization", "sk-xxxxxxxxxxxxxxxx" 'Replace with your API key

    

    'Set body for API call with prompt and parameters

    Set body = CreateObject("Scripting.Dictionary")

    

    'Get item name from cell A1

    Dim item As String

    item = Range("A1").Value

    

    'Set prompt to chat about the item using ChatGPT's persona

    body.Add "prompt", "The following is a conversation with ChatGPT, an AI assistant that can help you with Excel tasks. ChatGPT knows how to use VBA and can generate code snippets for you.\n\nHuman: Hi, I want to chat about " & item & ".\nChatGPT:"

    

    'Set parameters for completion such as temperature, max_tokens, etc.

    body.Add "temperature", 0.5 'Lower temperature means more predictable responses

    body.Add "max_tokens", 50 'Maximum number of tokens to generate

    body.Add "stop", "\nHuman:" 'Stop generating when encountering this sequence

    

     'Create a new request object

     Set request = CreateObject("MSXML2.XMLHTTP")

     

     'Send a POST request with the url, headers and body as JSON string

     request.Open "POST", url, False

     For Each Key In headers.keys

        request.setRequestHeader Key, headers(Key)

     Next Key

     

     request.send JsonConverter.ConvertToJson(body)

     

     'Get the response text as JSON object and extract the generated text

     response = request.responseText

     Set json = JsonConverter.ParseJson(response)

     

     Dim generated_text As String

     generated_text = json("choices")(1)("text")

     

     

    

End Sub


Monday, February 27, 2023

Error Databricks 'charindex'. This function is neither a registered temporary function nor a permanent function registered in the database 'test'.; line 6 pos 32


Error in DataBricks SQL 'charindex'. This function is neither a registered temporary function nor a permanent function registered in the database 'test'.; line 6 pos 32


Instead of this 
CHARINDEX('.', JDEAccount)

Use This 

INSTR(JDEAccount, '.')

Sunday, February 26, 2023

Generate Insert SQL Script from SQL Server to DataBricks Azure

DECLARE

    @TABLENAME VARCHAR(MAX) ='GLaccountsEIMcsv',

    @FILTER_C VARCHAR(MAX)=''   -- where SLNO = 15 or some value

DECLARE @TABLE_NAME VARCHAR(MAX),

        @CSV_COLUMN VARCHAR(MAX),

        @QUOTED_DATA VARCHAR(MAX),

        @SQLTEXT VARCHAR(MAX),

        @FILTER VARCHAR(MAX) 

SET @TABLE_NAME=@TABLENAME

SELECT @FILTER=@FILTER_C

SELECT @CSV_COLUMN=STUFF

(

    (

     SELECT ',['+ NAME +']' FROM sys.all_columns 

     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 

     is_identity!=1 FOR XML PATH('')

    ),1,1,''

)

SELECT @QUOTED_DATA=STUFF

(

    (

     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns 

     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 

     is_identity!=1 FOR XML PATH('')

    ),1,1,''

)

-- FOR SQL SERVER

--SELECT @SQLTEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER

-- FOR DATABRICKS SQL

SELECT @SQLTEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'   VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER

EXECUTE (@SQLTEXT)



SQL

https://www.mytecbits.com/microsoft/sql-server/auto-generate-insert-statements

Sunday, February 12, 2023

Create Table Databricks select into a temp table

 %sql

CREATE TABLE tblBU_list_XX40_Desc_01 as

select * from tblBU_list_XX40_Desc