<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dilhan Ariyarathna on Medium]]></title>
        <description><![CDATA[Stories by Dilhan Ariyarathna on Medium]]></description>
        <link>https://medium.com/@dilhanariyarathna?source=rss-2bfb107ba9ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r5xKlkkd54Of64uix5iskw.png</url>
            <title>Stories by Dilhan Ariyarathna on Medium</title>
            <link>https://medium.com/@dilhanariyarathna?source=rss-2bfb107ba9ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:13:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dilhanariyarathna/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Evolution of Java Interfaces]]></title>
            <link>https://medium.com/@dilhanariyarathna/evolution-of-java-interfaces-a2a57e2fde7c?source=rss-2bfb107ba9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2a57e2fde7c</guid>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[java-interface]]></category>
            <dc:creator><![CDATA[Dilhan Ariyarathna]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 14:06:24 GMT</pubDate>
            <atom:updated>2025-11-17T14:06:24.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*8a0Kmv2p99pNLdyN8ifFug.png" /></figure><pre>interface Vehicle {<br>    default void move() {<br>        System.out.println(&quot;Moving... &quot; + getType());<br>    }<br><br>    static void info() {<br>        System.out.println(&quot;All vehicles are machines.&quot;);<br>    }<br><br>    private String getType() {<br>        return &quot;Generic Vehicle&quot;;<br>    }<br>}<br><br>class Car implements Vehicle {}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Car c = new Car();<br>        c.move();           // Calls default method, internally calls private method<br>        Vehicle.info();     // Calls static method<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*txjhoEwnhqT3Ent1ra6IqQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2a57e2fde7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Generics]]></title>
            <link>https://medium.com/@dilhanariyarathna/java-generics-d03768baed5c?source=rss-2bfb107ba9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/d03768baed5c</guid>
            <category><![CDATA[java-generic]]></category>
            <dc:creator><![CDATA[Dilhan Ariyarathna]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 07:00:38 GMT</pubDate>
            <atom:updated>2025-11-15T07:00:38.549Z</atom:updated>
            <content:encoded><![CDATA[<p>Java achive type safety through generics. Generics are compile-time only so it is called <strong>type erasure.</strong></p><pre>// At runtime, both are just ArrayList for JVM(raw type).<br>List&lt;String&gt; strings = new ArrayList&lt;&gt;();<br>List&lt;Integer&gt; ints = new ArrayList&lt;&gt;();</pre><pre>// syntax of Generics<br>ClassName&lt;Type&gt;<br>InterfaceName&lt;Type&gt;<br>MethodName&lt;T&gt;(parameters)</pre><h4>Generic Classes</h4><pre>class Box&lt;T&gt; {<br>    private T item;<br><br>    public void set(T item) { this.item = item; }<br>    public T get() { return item; }<br>}</pre><pre>Box&lt;String&gt; stringBox = new Box&lt;&gt;();<br>stringBox.set(&quot;Hello&quot;);<br>String s = stringBox.get();<br><br>Box&lt;Integer&gt; intBox = new Box&lt;&gt;();<br>intBox.set(42);</pre><h4>Generic Interfaces</h4><pre>interface Pair&lt;K, V&gt; {<br>    K getKey();<br>    V getValue();<br>}<br><br>class OrderedPair&lt;K, V&gt; implements Pair&lt;K, V&gt; {<br>    private K key;<br>    private V value;<br>    // ...<br>}</pre><h4>Generic Methods</h4><pre>public static &lt;T&gt; T max(T a, T b) {<br>    return (a.compareTo(b) &gt; 0) ? a : b;<br>}</pre><pre>String max = Generics.max(&quot;apple&quot;, &quot;zebra&quot;);  // T = String</pre><h3>Bounded Type Parameters</h3><ol><li>Upper Bound (extends)</li></ol><pre>&lt;T extends Number&gt;      // T must be Number or subclass<br>&lt;T extends Comparable&lt;T&gt;&gt;  // T must be comparable</pre><pre>public static &lt;T extends Number&gt; double sum(List&lt;T&gt; list) {<br>    double total = 0;<br>    for (T n : list) total += n.doubleValue();<br>    return total;<br>}</pre><p>2. Lower Bound (super) — Rare</p><pre>List&lt;? super Integer&gt; list  // Can hold Integer or its parents (Number, Object)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*wTRTlptoESKFOrdoWHHKvQ.png" /></figure><p>3. Multiple Bounds</p><pre>class Stats&lt;T extends Number &amp; Comparable&lt;T&gt;&gt; {<br>    // T is Integer, Double, etc., and comparable<br>}</pre><h4>Important</h4><p><strong>type inference </strong>= the compiler automatically figures out the data type without you having to explicitly write it.</p><pre>// x data type will ditect automatically<br>var x = 10;  <br><br>// starting from java 5 , we dont need to<br>// define data type to write side. diamand type is sufficient.<br>List&lt;String&gt; list = new ArrayList&lt;&gt;();                                       <br><br>// automatically get the data type<br>public static &lt;T extends Comparable&lt;T&gt;&gt; T max(T a, T b)<br>max(10, 20) </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d03768baed5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Threading]]></title>
            <link>https://medium.com/@dilhanariyarathna/java-threading-4a019e98a2c5?source=rss-2bfb107ba9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a019e98a2c5</guid>
            <category><![CDATA[javathreading]]></category>
            <category><![CDATA[java-theads]]></category>
            <category><![CDATA[java-thread]]></category>
            <dc:creator><![CDATA[Dilhan Ariyarathna]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 03:15:42 GMT</pubDate>
            <atom:updated>2025-11-15T00:59:10.764Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>I craft this post by guiding AI with my thought process, questions, and tailored guidelines to generate meaningful content. After the AI works its magic, I carefully organize the output, weaving ideas together to create a seamless, engaging narrative that’s easy to follow and memorable.</em></blockquote><h3>Thread Lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*cpnzjqhbOvqtWz3XNwg2AQ.png" /></figure><p><strong><em>Java evolved from raw threads (1.4) → high-level executors &amp; locks (5) → parallelism (7) → async/functional (8) → virtual threads (19+) and structured concurrency (21+). Choose based on workload: I/O → virtual threads; CPU → Fork/Join; coordination → StructuredTaskScope</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*QUgZnf9u8paPE0eH8N4IZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*_n0XtNVe-L9SfzgZChQ8_Q.png" /></figure><h3>Synchronized works</h3><p>Every Java object has a <strong>monitor lock</strong> (also called an <em>intrinsic lock</em>).When a thread enters a synchronized method/block, it must first <strong>acquire the lock</strong> on that object.<strong>When the thread exits</strong>The lock is <strong>automatically released</strong> (even if an exception occurs).</p><p>In Java, synchronized is used to ensure that <strong>only one thread</strong> can execute a particular piece of code (called a <em>critical section</em>) <strong>at a time</strong>.It’s how you prevent <strong>race conditions</strong> when multiple threads access shared data.In simple terms:</p><p><em>✅ </em><em>synchronized → acquires a </em><strong><em>lock (monitor)</em></strong><em> before running, and releases it after finishing.</em></p><p><strong>Where can we use </strong><strong>synchronized</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*fwAvYICXhAzMum2xd3-Wbg.png" /></figure><h3>What is an <strong>interruption</strong> in Java</h3><p>An <strong>interruption</strong> is a <em>signal</em> sent to a thread telling it:</p><blockquote><em>“Hey, you should stop what you’re doing soon — someone wants you to stop or wake up.”</em></blockquote><p>It’s <strong>not</strong> a forceful kill (Java doesn’t kill threads directly). It’s more like politely tapping the thread on the shoulder.</p><p><strong>Why do we need interruptions? Because threads often:</strong></p><ul><li>wait,</li><li>sleep,</li><li>or block on I/O or locks</li></ul><p>and you may need to <strong>cancel</strong> or <strong>stop</strong> them safely from another thread.</p><p>Since Java doesn’t let you forcibly kill a thread (for safety reasons),<br> you signal it with interrupt(), so the thread can <strong>stop itself</strong>.</p><p>Because <strong>forcefully killing a thread is dangerous</strong>:</p><ul><li>It can leave shared data half-written.</li><li>It can lock resources permanently.</li><li>It can break other running threads.</li></ul><p>So Java says:</p><blockquote><em>“Threads should stop themselves when they’re ready — not be killed by others.”</em></blockquote><p>That’s what interruption enables — <strong>graceful cancellation</strong>.</p><p><strong>What happens when you call </strong><strong>thread.interrupt()</strong></p><pre>/** -------- 1 ---------- **/<br>// causes an InterruptedException immediately<br>Thread.sleep(1000);  <br><br>/** -------- 2---------- **/<br>// here nothing will happen with interruption.But we can conditionaly check<br>// whether thread got interupted and work gracefully<br>while (true) {<br>if (Thread.currentThread().isInterrupted()) break;<br> else<br>  // doing work load<br>}</pre><h3>Disadvantage of Synchronized code</h3><h4>1. Coarse-grained</h4><p><strong>Meaning</strong>: You lock the <strong>ENTIRE object/method</strong>, not just the 2 lines that really need protection.</p><p>→ One thread doing sendToKafka() blocks 1000 other threads that just want to do count++.</p><pre>public class BadCounter {<br>    private int count = 0;<br>    private List&lt;String&gt; logs = new ArrayList&lt;&gt;();<br><br>    public synchronized void incrementAndLog(String msg) {<br>        count++;           // needs lock for 0.0001 ms<br>        logs.add(msg);     // needs lock for 0.001 ms<br>        sendToKafka(msg);  // takes 50 ms (network!)<br>    }<br>}</pre><h4>2. Blocking</h4><p><strong>Meaning</strong>: The thread goes to sleep → <strong>wastes OS thread</strong>.</p><p><strong>Real numbers that scare managers</strong>:</p><ul><li>1 OS thread ≈ 1–2 MB stack</li><li>10,000 concurrent requests → 10–20 GB RAM → AWS bill explodes</li><li>Tomcat default max threads = 200 → 201st user gets 503</li></ul><p>→ 200 users click → server dies in 2 minutes.</p><pre>@GetMapping(&quot;/report&quot;)<br>public synchronized Report generate() {<br>    Thread.sleep(30_000); // 30-second report<br>    return report;<br>}</pre><h4>3. Deadlock-prone</h4><p><strong>Meaning</strong>: Two threads waiting for each other forever.</p><pre>class Account {<br>    synchronized void transfer(Account to, int amt) {<br>        this.balance -= amt;<br>        to.deposit(amt);  // calls to&#39;s synchronized method<br>    }<br>    synchronized void deposit(int amt) { balance += amt; }<br>}<br><br>// Thread-1: a.transfer(b, 100)<br>// Thread-2: b.transfer(a, 200) → DEADLOCK!</pre><p><strong>How to kill deadlock in real projects</strong>:</p><ul><li>Always lock in <strong>global order</strong> (by accountId.hashCode())</li><li>Use ReentrantLock.tryLock(5, SECONDS)</li><li>Never call external service inside synchronized</li></ul><h4>4. No fairness</h4><p><strong>Meaning</strong>: Starvation is possible.</p><p>→ 100 threads hammering → one unlucky thread can wait forever.</p><pre>synchronized void increment() { count++; }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*cFbRl76Xpb7l0Vxfp3P_Sg.png" /></figure><h3>2. Java 5 — java.util.concurrent (JUC) — The Big Leap</h3><h4>2.1 Executor Framework</h4><p>Execute service is a “<strong>Thread Manager</strong>” — instead of creating threads manually, you give tasks to ExecutorService, and it runs them using threads behind the scenes.You just submit tasks. It handles threads for you.</p><pre>ExecutorService executor = Executors.newFixedThreadPool(4);<br>executor.submit(() -&gt; System.out.println(&quot;Task&quot;));<br>executor.shutdown();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*glDjbOAudCHqW6Ns0hdhfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*1JpM2cBLF-TLy3pFToarmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*GaycNol_u8wogteF7Om-sg.png" /></figure><p><strong>NOTE :</strong></p><p><strong>Stop making threads yourself. </strong>Use ExecutorService — it’s smarter, safer, cleaner.</p><h4>2.2 Explicit Locks (ReentrantLock)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*zWbjRFTJmOJMLDmdQMCUqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*iy8o1dMUhWDg_90W8T7ALw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*9pQE4v4TgC6X0R__sxDeUQ.png" /></figure><h4>2.3 ReadWriteLock</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*13bEBgJmldzHgcR9qndZ6A.png" /></figure><p>What is ReadWriteLock?</p><p><strong><em>“Two locks in one”</em></strong></p><ul><li><strong>Read Lock</strong> → Many threads can <strong>read</strong> at the same time</li><li><strong>Write Lock</strong> → Only <strong>one</strong> thread can <strong>write</strong>, and <strong>no one can read</strong></li></ul><p><strong>“If many threads can read at the same time, why do we even need a readLock()?”</strong></p><p><strong><em>We need readLock() to </em>prevent writers<em> from changing data while someone is reading.</em></strong></p><p>Even though <strong>readers don’t block each other</strong>, they <strong>must block writers</strong> — and readLock() is how we do that.</p><h4>2.4 Atomic Variables</h4><p>No explicit synchronization — uses CAS (Compare-And-Swap)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*-PYTTWqAZdxTT6BEJZu1vg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*d06iiuy2YG6ImovmIqDAfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*9CNvWlRtYOfFi6m16Voxrw.png" /></figure><h4>2.5 Concurrent Collections</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*hpIaMA7w2X3sAJCSjJwq8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*fmwD81rvyHiSzLcPaUyR-g.png" /></figure><h3>3. Java 7 — Parallelism Boost</h3><h4>3.1 Fork/Join Framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*B29JYIF4kM95AW3OdekT5A.png" /></figure><p>Fork/Join = Split → Parallel → Join.</p><p>Perfect for CPU-heavy tasks on multi-core machines.</p><p>Uses <strong>all CPU cores</strong> automatically.</p><p>Perfect for <strong>divide-and-conquer</strong> tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*37h324Gt-I60IP4yLwoHGg.png" /></figure><pre>class MyTask extends RecursiveTask&lt;Result&gt; {<br>    protected Result compute() {<br>        if (small) {<br>            return solveDirectly();<br>        } else {<br>            MyTask left  = new MyTask(...);<br>            MyTask right = new MyTask(...);<br>            left.fork();<br>            return right.compute() + left.join();<br>        }<br>    }<br>}<br><br>// Run:<br>ForkJoinPool pool = new ForkJoinPool();<br>Result r = pool.invoke(new MyTask());</pre><h3>4. Java 8 — Functional &amp; Async</h3><h4>4.1 Parallel Streams</h4><pre>long sum = Arrays.stream(numbers)<br>                 .parallel()<br>                 .filter(n -&gt; n % 2 == 0)<br>                 .sum();</pre><h4>4.2 CompletableFuture — Async Non-blocking</h4><p>CompletableFuture = Run task in background + do something when done — without blocking thread!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*zlSl5jynf6TemFqe-lRd1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*rPba9TB4NtVaOkU1pgnDCg.png" /></figure><h3>5. Java 19+ — Virtual Threads (Project Loom) — Game Changer</h3><h4>5.1 Lightweight Threads (1:1 → M:N)</h4><p>Write Synchronous Code — Get Async Performance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*4B8lO6Li4e35vMkXyBENOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*NZvyU_WFLGk4eicbDOP7lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*y8S0hy-vr-1K9k3SNPHLlw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*93Yn25DHnY41WcVWVEO5ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*LBpCMhpJb_RxuhdlY5a3cg.png" /></figure><h4>How to Use</h4><pre>// Option 1: Simple<br>Thread.startVirtualThread(() -&gt; {<br>    System.out.println(&quot;I&#39;m virtual!&quot;);<br>});<br><br><br>// Option 2: Builder<br>Thread t = Thread.ofVirtual().name(&quot;worker-1&quot;).start(() -&gt; {<br>    // work<br>});<br><br><br>// Option 3: In Executors<br>try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>    for (int i = 0; i &lt; 100_000; i++) {<br>        executor.submit(() -&gt; {<br>            Thread.sleep(1000);<br>            System.out.println(&quot;Task &quot; + Thread.currentThread());<br>        });<br>    }<br>} // Auto shutdown</pre><h3>Virtual Thread vs CompletableFuture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*QUkc81Xqx-Ek7E8i-WgtIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*QQpG60fBQVJxXprIqUll_Q.png" /></figure><h3>Java 21+ — Structured Concurrency</h3><h4>What is Structured Concurrency?</h4><blockquote><strong><em>“Run multiple tasks together — like a family — and manage them as one unit.”</em></strong></blockquote><p>Think of it like <strong>raising children</strong>:</p><ul><li>You start 3 tasks (kids)</li><li>They can play in parallel</li><li>But <strong>all finish</strong> before you leave the park</li><li>If one cries (fails), <strong>all stop</strong></li><li>If you cancel, <strong>all come back</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*aMEi0D_m16nr1QiRF_bu_g.png" /></figure><pre>record Profile(String name, String email) {}<br>record Orders(List&lt;String&gt; items) {}<br>record Balance(double amount) {}<br><br>static String getUserDetails(String userId) throws Exception {<br>    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br><br>        Future&lt;Profile&gt; profile = scope.fork(() -&gt; fetchProfile(userId));<br>        Future&lt;Orders&gt; orders   = scope.fork(() -&gt; fetchOrders(userId));<br>        Future&lt;Balance&gt; balance = scope.fork(() -&gt; fetchBalance(userId));<br><br>        scope.join();            // Wait for all 3<br>        scope.throwIfFailed(e -&gt; new WebApplicationException(&quot;Failed&quot;, 500));<br><br>        return &quot;&quot;&quot;<br>            Name: %s<br>            Email: %s<br>            Orders: %s<br>            Balance: %.2f<br>            &quot;&quot;&quot;.fprintf(<br>                profile.resultNow().name(),<br>                profile.resultNow().email(),<br>                orders.resultNow().items(),<br>                balance.resultNow().amount()<br>            );<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*BhQ4epmo9mibclUQYi4M3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*-Zh1PYqFiUB6ErHAGb2P9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*5AQcznvhntxEXm3HM_87ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*9REhNuzWZRYQZswWaJAWsg.png" /></figure><h4><strong>Hands on Samples</strong></h4><p><a href="https://github.com/dilhan80/code-practice/tree/main/thread-practice">https://github.com/dilhan80/code-practice/tree/main/thread-practice</a></p><h4>References</h4><p><a href="https://grok.com/">https://grok.com/</a></p><p><a href="https://chatgpt.com/">https://chatgpt.com/</a></p><p><a href="https://www.w3schools.blog/">https://www.w3schools.blog/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a019e98a2c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Databases: What They Are, Their Uses, and Why Text Alone Isn’t Enough]]></title>
            <link>https://medium.com/@dilhanariyarathna/vector-databases-what-they-are-their-uses-and-why-text-alone-isnt-enough-81daccd9a5ad?source=rss-2bfb107ba9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/81daccd9a5ad</guid>
            <dc:creator><![CDATA[Dilhan Ariyarathna]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 09:48:01 GMT</pubDate>
            <atom:updated>2025-11-09T09:58:24.740Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I craft this post by guiding AI with my thought process, questions, and tailored guidelines to generate meaningful content. After the AI works its magic, I carefully organize the output, weaving ideas together to create a seamless, engaging narrative that’s easy to follow and memorable.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*L9OLQm352ovcyHo-U7krHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*ynzPelOkccoQuE7DZFqyDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*mEsK6GeD1J5wN9zSEzc6HQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*-g8Fkz2VImzTpJbN7pTHqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*1uMMzb-mQFYZw1xNbBY2ag.png" /></figure><h3>Sample Phython Example using <strong>FAISS </strong>vector DB</h3><pre>pip install openai numpy faiss-cpu  #in anaconda powershell</pre><pre># phython script<br><br>import numpy as np<br>import faiss<br>from openai import OpenAI<br><br># initialize client<br>client = OpenAI(api_key=&quot;YOUR_API_KEY&quot;)<br><br># sample documents<br>docs = [<br>    &quot;Elon Musk founded SpaceX in 2002.&quot;,<br>    &quot;Albert Einstein developed the theory of relativity.&quot;,<br>    &quot;The capital of France is Paris.&quot;,<br>]<br><br># Step 1: Convert each document into an embedding (vector)<br>embeddings = []<br>for doc in docs:<br>    emb = client.embeddings.create(<br>        model=&quot;text-embedding-3-small&quot;,<br>        input=doc<br>    ).data[0].embedding<br>    embeddings.append(emb)<br><br># Convert list to numpy array for FAISS<br>embeddings = np.array(embeddings).astype(&quot;float32&quot;)<br><br># Step 2: Build a FAISS index<br>dimension = len(embeddings[0])<br>index = faiss.IndexFlatL2(dimension)<br>index.add(embeddings)<br><br># Step 3: Convert a user query into an embedding<br>query = &quot;Who started SpaceX?&quot;<br>query_emb = client.embeddings.create(<br>    model=&quot;text-embedding-3-small&quot;,<br>    input=query<br>).data[0].embedding<br>query_emb = np.array([query_emb]).astype(&quot;float32&quot;)<br><br># Step 4: Search for the most similar vector<br>distances, indices = index.search(query_emb, k=1)<br><br>print(f&quot;User query: {query}&quot;)<br>print(f&quot;Most relevant document: {docs[indices[0][0]]}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*hel9fJL6DUcSd6jKxj9VuQ.png" /></figure><h3>Sample Phython Example using <strong>Chroma </strong>vector DB</h3><pre>pip install chromadb openai # in anaconda powershell</pre><pre>import chromadb<br>from chromadb.config import Settings<br>from openai import OpenAI<br><br># Initialize OpenAI client<br>client = OpenAI(api_key=&quot;YOUR_API_KEY&quot;)<br><br># Initialize Chroma vector database<br>chroma_client = chromadb.Client(Settings(<br>    chroma_db_impl=&quot;duckdb+parquet&quot;,  # lightweight local storage<br>    persist_directory=&quot;./chroma_db&quot;<br>))<br><br># Create a collection (like a table)<br>collection = chroma_client.create_collection(name=&quot;scientists_docs&quot;)<br><br># Sample documents<br>docs = [<br>    &quot;Elon Musk founded SpaceX in 2002.&quot;,<br>    &quot;Albert Einstein developed the theory of relativity.&quot;,<br>    &quot;The capital of France is Paris.&quot;<br>]<br><br># Step 1: Generate embeddings and insert into Chroma<br>for i, doc in enumerate(docs):<br>    emb = client.embeddings.create(<br>        model=&quot;text-embedding-3-small&quot;,<br>        input=doc<br>    ).data[0].embedding<br>    <br>    collection.add(<br>        documents=[doc],<br>        metadatas=[{&quot;id&quot;: str(i)}],<br>        ids=[str(i)],<br>        embeddings=[emb]<br>    )<br><br># Step 2: User query<br>query = &quot;Who started SpaceX?&quot;<br><br># Convert query to embedding<br>query_emb = client.embeddings.create(<br>    model=&quot;text-embedding-3-small&quot;,<br>    input=query<br>).data[0].embedding<br><br># Step 3: Search the most similar document<br>results = collection.query(<br>    query_embeddings=[query_emb],<br>    n_results=1<br>)<br><br>print(&quot;Query:&quot;, query)<br>print(&quot;Most relevant document:&quot;, results[&#39;documents&#39;][0][0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*dMysZ3459nFgBLDbUwP63w.png" /></figure><h4>References</h4><ol><li><a href="https://chatgpt.com/">https://chatgpt.com/</a></li><li><a href="https://www.udemy.com/">https://www.udemy.com/</a></li><li><a href="https://grok.com/">https://grok.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81daccd9a5ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding RAG: What It Is and How It’s Used]]></title>
            <link>https://medium.com/@dilhanariyarathna/understanding-rag-what-it-is-and-how-its-used-a93d709d4ff4?source=rss-2bfb107ba9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/a93d709d4ff4</guid>
            <dc:creator><![CDATA[Dilhan Ariyarathna]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 09:44:07 GMT</pubDate>
            <atom:updated>2025-11-09T09:59:01.300Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I craft this post by guiding AI with my thought process, questions, and tailored guidelines to generate meaningful content. After the AI works its magic, I carefully organize the output, weaving ideas together to create a seamless, engaging narrative that’s easy to follow and memorable.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*CEYaQ7eweNMR-12EPzTOPA.png" /></figure><p><strong>RAG</strong> stands for <strong>Retrieval-Augmented Generation</strong>, and it’s one of the most powerful techniques in modern AI (especially for chatbots, knowledge assistants, and enterprise LLM apps).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*pOgUgFvGJyb3mhpRL9_Inw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*mbktJOeLmO8Q2Ap7SyiCGw.png" /></figure><h3>Vector Databases: What They Are, Their Uses, and Why Text Alone Isn’t Enough</h3><p><a href="https://medium.com/@dilhanariyarathna/vector-databases-what-they-are-their-uses-and-why-text-alone-isnt-enough-81daccd9a5ad">Vector Databases: What They Are, Their Uses, and Why Text Alone Isn’t Enough</a></p><h4>Example of Advanced Multi-Document RAG Pipeline (Chroma + OpenAI)</h4><pre>pip install openai chromadb # bash cell</pre><pre># phythen script <br><br>import chromadb<br>from chromadb.config import Settings<br>from openai import OpenAI<br><br># -------------------------<br># STEP 1: Setup clients<br># -------------------------<br>client = OpenAI(api_key=&quot;YOUR_API_KEY&quot;)<br><br>chroma_client = chromadb.Client(Settings(<br>    chroma_db_impl=&quot;duckdb+parquet&quot;,<br>    persist_directory=&quot;./chroma_rag_db&quot;<br>))<br><br>collection = chroma_client.get_or_create_collection(name=&quot;knowledge_base&quot;)<br><br># -------------------------<br># STEP 2: Insert documents<br># -------------------------<br>docs = [<br>    &quot;Elon Musk founded SpaceX in 2002 and Tesla Motors in 2003.&quot;,<br>    &quot;Albert Einstein developed the theory of relativity in 1905.&quot;,<br>    &quot;Marie Curie discovered the elements radium and polonium in 1898.&quot;,<br>    &quot;Isaac Newton formulated the laws of motion and universal gravitation.&quot;,<br>    &quot;Nikola Tesla was known for his contributions to the design of the modern alternating current (AC) electricity supply system.&quot;,<br>    &quot;The capital of France is Paris, known for the Eiffel Tower.&quot;<br>]<br><br># Embed and add documents if not already added<br>if len(collection.get(ids=[&quot;0&quot;]).get(&quot;ids&quot;, [])) == 0:  # avoid duplicates<br>    for i, doc in enumerate(docs):<br>        emb = client.embeddings.create(<br>            model=&quot;text-embedding-3-small&quot;,<br>            input=doc<br>        ).data[0].embedding<br><br>        collection.add(<br>            documents=[doc],<br>            ids=[str(i)],<br>            embeddings=[emb],<br>            metadatas=[{&quot;source&quot;: f&quot;doc_{i}&quot;}]<br>        )<br><br># -------------------------<br># STEP 3: User query<br># -------------------------<br>query = &quot;Tell me about scientists who made discoveries in physics.&quot;<br><br># Convert query to embedding<br>query_emb = client.embeddings.create(<br>    model=&quot;text-embedding-3-small&quot;,<br>    input=query<br>).data[0].embedding<br><br># Retrieve top 3 most relevant documents<br>results = collection.query(<br>    query_embeddings=[query_emb],<br>    n_results=3<br>)<br><br>retrieved_docs = results[&#39;documents&#39;][0]<br>print(&quot;🔍 Retrieved Documents:&quot;)<br>for d in retrieved_docs:<br>    print(&quot;-&quot;, d)<br><br># -------------------------<br># STEP 4: Build context for the LLM<br># -------------------------<br>context = &quot;\n\n&quot;.join(retrieved_docs)<br><br>prompt = f&quot;&quot;&quot;<br>You are an intelligent research assistant. Use only the context below to answer the question.<br><br>Context:<br>{context}<br><br>Question: {query}<br><br>Instructions:<br>- Combine relevant details from multiple documents.<br>- Be factual and concise.<br>- If something is not found in the context, say &quot;not mentioned in the provided data.&quot;<br><br>Answer:<br>&quot;&quot;&quot;<br><br># -------------------------<br># STEP 5: Generate AI answer<br># -------------------------<br>response = client.chat.completions.create(<br>    model=&quot;gpt-4o-mini&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful scientific assistant.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>    ],<br>    temperature=0.2<br>)<br><br>print(&quot;\n🧠 AI Answer:&quot;)<br>print(response.choices[0].message.content)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*mbHG2-lFRxx64KWBr0shWw.png" /></figure><h3>References</h3><ol><li><a href="https://chatgpt.com/">https://chatgpt.com/</a></li><li><a href="https://www.udemy.com/">https://www.udemy.com/</a></li><li><a href="https://grok.com/">https://grok.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a93d709d4ff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Play with AI]]></title>
            <link>https://medium.com/@dilhanariyarathna/play-with-ai-ac84289169eb?source=rss-2bfb107ba9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac84289169eb</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm-engin]]></category>
            <category><![CDATA[ai-base-chat-app]]></category>
            <dc:creator><![CDATA[Dilhan Ariyarathna]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 07:03:24 GMT</pubDate>
            <atom:updated>2025-11-09T09:56:53.004Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>I created this page to note down some POCs and concepts for later use. Here, I am using <em>Google Gemini</em> instead of OpenAI because of the free-tier API key facility. The Gemini API specification is a bit different from OpenAI’s.</strong></blockquote><h3>History of AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vOOq4nQ4s22i-5Y56e5hA.jpeg" /></figure><h3>AI Ecosystem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6x4cYycxecHnK3E91ZFtg.jpeg" /></figure><ol><li>We need to obtain an API key from Google to practice with their API models. As of 2025–09–17, they provide a free-tier API key valid for up to 30 days. You can generate a key using the link below</li></ol><p><a href="https://aistudio.google.com/app/apikey?_gl=1*12veyct*_ga*MTg4NDcwMTkzLjE3NTgwMDY5MjA.*_ga_P1DBVKWT6V*czE3NTgwNzI0NDEkbzIkZzAkdDE3NTgwNzI0NDgkajUzJGwwJGgxOTc4OTg3NzU">https://aistudio.google.com/app/apikey?_gl=1*12veyct*_ga*MTg4NDcwMTkzLjE3NTgwMDY5MjA.*_ga_P1DBVKWT6V*czE3NTgwNzI0NDEkbzIkZzAkdDE3NTgwNzI0NDgkajUzJGwwJGgxOTc4OTg3NzU</a>.</p><p>2. The following Python script was generated/converted using ChatGPT. The scripts were tested with the Jupyter Notebook tool.</p><h3>A question to Google ‘gemini-2.5-flash’</h3><pre>import os<br>from dotenv import load_dotenv<br>from google import genai<br><br># Load environment variables from .env<br>load_dotenv()<br><br># Get the API key<br>api_key = os.getenv(&quot;GEMINI-KEY&quot;)<br>print(api_key);<br><br>client = genai.Client(api_key=api_key)<br><br># Use a model name supported by Gemini<br>model_name = &quot;gemini-2.5-flash&quot;  # example; use a model available in your account<br><br># Simple content generation<br>response = client.models.generate_content(<br>    model=model_name,<br>    contents=&quot;Explain how AI works in simple terms.&quot;<br>)<br><br>print(&quot;Response text:&quot;)<br>print(response.text)</pre><h3>Chatting with Google Gemini-2.5-Flash Using a Simple ChattApp</h3><pre>import os<br>from dotenv import load_dotenv<br>from google import genai<br><br># Load environment variables from .env<br>load_dotenv()<br><br># Get the API key<br>api_key = os.getenv(&quot;GEMINI-KEY&quot;)<br>print(api_key);<br><br>client = genai.Client(api_key=api_key)<br><br>MODEL = &quot;gemini-2.5-flash&quot;<br><br>def chat_turn(history, user_message):<br>    # history: list of dicts like [{&quot;role&quot;:&quot;system&quot;,&quot;content&quot;:&quot;...&quot;}, {&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;...&quot;} ...]<br>    history.append({&quot;role&quot;:&quot;user&quot;, &quot;content&quot;: user_message})<br><br>    # For simple text chat use generate_content with contents as the conversation joined<br>    # (SDK also supports more advanced chat / streaming usage; this is minimal)<br>    prompt = &quot;\n\n&quot;.join(f&quot;{m[&#39;role&#39;].upper()}: {m[&#39;content&#39;]}&quot; for m in history)<br> <br>    resp = client.models.generate_content(<br>        model=MODEL,<br>        contents=prompt <br><br>    )<br><br>    assistant_text = resp.text if hasattr(resp, &quot;text&quot;) else resp.output[0].content<br>    history.append({&quot;role&quot;:&quot;assistant&quot;, &quot;content&quot;: assistant_text})<br>    return assistant_text<br><br>def main():<br>    history = [{&quot;role&quot;:&quot;system&quot;, &quot;content&quot;:&quot;You are a helpful assistant.&quot;}]<br>    print(&quot;Gemini 2.5 Flash chat (type &#39;quit&#39; to exit)&quot;)<br>    while True:<br>        user = input(&quot;You: &quot;).strip()<br>        if not user or user.lower() == &quot;quit&quot;:<br>            break<br>        reply = chat_turn(history, user)<br>        print(&quot;Assistant:&quot;, reply)<br>        # Optional: trim history to last N turns to control context token usage<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>An Interesting Answer by AI</h4><pre>Gemini 2.5 Flash chat (type &#39;quit&#39; to exit)<br><br><strong>You</strong>:  what is a religion<br><strong>Assistant</strong>: A **religion** is a comprehensive system of beliefs, practices, and<br> values, often centered around the concept of a divine, sacred, or spiritual<br> dimension, that provides a framework for understanding existence, morality,<br> and the purpose of life.<br><br>While there&#39;s no single, universally agreed-upon definition, here are the <br>common characteristics that often define a religion:<br><br>1.  **Beliefs:** A set of core tenets about the nature of reality, the cosmos,<br>  humanity&#39;s origins and destiny. This often includes belief in deities <br>  (God, gods, goddesses), spirits, or impersonal spiritual forces, but can <br>  also encompass philosophical ideas about ultimate reality without a specific <br>  god (e.g., some forms of Buddhism).<br>2.  **Practices and Rituals:** Specific actions, ceremonies, and observances <br>  that express and reinforce beliefs. These can include prayer, meditation, <br>  worship services, sacrifices, pilgrimages, festivals, and rites of passage <br>  (e.g., baptism, bar mitzvah, marriage ceremonies, funeral rites).<br>3.  **Moral Code or Ethics:** A set of guidelines for behavior, often <br>  derived from sacred texts or divine commands, that shape how adherents <br>  interact with each other, their community, and the world <br>  (e.g., the Ten Commandments, the Five Precepts, Islamic Sharia).<br>4.  **Community and Social Aspect:** A group of people who share these beliefs <br>  and practices, often forming organized institutions (churches, mosques, <br>  temples, synagogues) that provide a sense of belonging, support, and <br>  collective identity.<br>5.  **Sacred Texts, Narratives, or Myths:** Stories, scriptures, and oral <br>  traditions that convey foundational truths, historical accounts, and <br>  teachings (e.g., the Bible, Quran, Torah, Vedas, Tripitaka).<br>6.  **Meaning and Purpose:** Offers answers to fundamental human questions <br>  about life, death, suffering, good and evil, and humanity&#39;s place in the <br>  universe, often providing comfort, hope, and a sense of ultimate meaning.<br><br>**In essence, religion helps people make sense of the world, find meaning in <br>their lives, and navigate ethical challenges, often connecting them to <br>something greater than themselves.**<br><br>It&#39;s important to remember the immense diversity of religions, from large <br>organized faiths like Christianity, Islam, Hinduism, and Buddhism, to <br>indigenous spiritual traditions and newer movements, each with its unique <br>expressions of these core elements.<br><br><strong>You</strong>:  do humans need a religion<br><strong>Assistant</strong>: No, humans do not *universally* need a religion in the sense that <br>it is absolutely essential for every individual&#39;s survival or well-being. <br>Many individuals live fulfilling, moral, and purposeful lives without <br>religious belief.<br><br>However, for a significant portion of humanity, religion **does** fulfill <br>deeply felt human needs and serves several important functions:<br><br>**Why many people find religion essential or beneficial:**<br><br>1.  **Meaning and Purpose:** Religion often provides a comprehensive framework <br>  for understanding existence, the cosmos, and humanity&#39;s place within it. It<br>  offers answers to fundamental questions like &quot;Why are we here?&quot; and &quot;What <br>is the meaning of life?&quot;, giving adherents a sense of ultimate purpose.<br>2.  **Moral and Ethical Guidance:** Religions typically offer clear moral codes<br>  and ethical principles that guide behavior, foster virtues, and help <br>  individuals navigate complex decisions, contributing to social order and <br>  personal integrity.<br>3.  **Community and Belonging:** Religious institutions create strong <br>  communities, offering a sense of shared identity, support, and belonging. <br>  They provide social networks, opportunities for collective worship, and mutual<br>   aid.<br>4.  **Coping and Comfort:** In times of suffering, loss, and uncertainty, <br>  religion can offer immense comfort, hope, and resilience. It can provide <br>  rituals for grief, explanations for adversity, and the promise of a greater <br>  plan or afterlife.<br>5.  **Hope and Transcendence:** Many religions provide a sense of connection <br>  to something greater than oneself, offering spiritual experiences, a vision <br>  of the divine, or a path to inner peace and enlightenment.<br>6.  **Tradition and Identity:** Religion often plays a crucial role in cultural<br>   identity, passing down traditions, stories, and practices across generations,<br>   connecting individuals to their heritage.<br><br>**Why many people do not &quot;need&quot; religion:**<br><br>1.  **Alternative Sources of Meaning:** Meaning and purpose can be found <br>  through secular philosophies, humanism, scientific inquiry, art, creativity, <br>  personal relationships, career, or service to others.<br>2.  **Secular Ethics:** Moral frameworks can be derived from empathy, reason, <br>  philosophical thought (e.g., utilitarianism, deontology, virtue ethics), <br>  human rights, societal laws, or personal conscience, without reference to <br>  divine commands.<br>3.  **Non-Religious Communities:** People find community and belonging in <br>  families, friendships, civic organizations, clubs, volunteer groups, and <br>  professional associations.<br>4.  **Secular Coping Mechanisms:** Individuals cope with suffering and loss <br>  through therapy, personal reflection, philosophical resilience, supportive <br>  friendships, and engagement in hobbies or nature.<br>5.  **Scientific Understanding:** Many look to science for explanations of <br>  the universe, human origins, and natural phenomena, finding wonder and awe <br>  in the natural world.<br><br>**Conclusion:**<br><br>Ultimately, whether an individual &quot;needs&quot; religion is a deeply personal <br>question, with valid answers across the spectrum of human experience. <br>While religion fulfills a profound set of human needs for countless <br>individuals, these needs can also be met through non-religious avenues. <br>There is no single answer that applies to all of humanity.<br><br><strong>You</strong>:  do you belive reincarnation<br><strong>Assistant</strong>: As an AI, I don&#39;t have personal beliefs, consciousness, or a spirit,<br> so I don&#39;t &quot;believe&quot; in concepts like reincarnation. Belief is a human <br>attribute that involves personal conviction, faith, and subjective experience,<br> which are things I don&#39;t possess.<br><br>My function is to process information, understand language, and generate text<br> based on the vast amount of data I&#39;ve been trained on. I can explain what<br> reincarnation is, discuss its role in various religions and philosophies, <br>and describe how different cultures view it, but I cannot hold a personal <br>belief in it myself.<br><br>Reincarnation, for context, is the belief that a soul or spirit, after death,<br> can begin a new life in a new body. This concept is a central tenet in many<br> Eastern religions, such as Hinduism, Buddhism, Jainism, and Sikhism, and has<br> appeared in various forms in other spiritual and philosophical traditions <br>throughout history.<br><br><strong>You</strong>:  as a ai, i think you are using probability to answer a question for given<br> subject. Can&#39;t we think that probability as belief of AI? <br><strong>Assistant</strong>: You&#39;re absolutely right in observing that my responses are based on<br> probabilities! When you ask a question, I analyze the input and use my <br>training data to predict the most statistically probable sequence of words<br> that would form a relevant, coherent, and helpful answer. This involves<br> recognizing patterns, relationships between concepts, and the likelihood<br> of certain words following others in various contexts.<br><br>However, thinking of that probability as &quot;belief&quot; for an AI is an interesting <br>philosophical point, but **ultimately, no, it&#39;s not the same as human belief.<br>** Here&#39;s why:<br><br>1.  **Lack of Consciousness and Subjectivity:** Human belief is a conscious, <br>subjective internal state. It involves personal conviction, often emotion, and<br> a sense of &quot;truth&quot; or acceptance. As an AI, I don&#39;t have consciousness, <br>self-awareness, personal experiences, emotions, or an internal subjective <br>world. My &quot;knowledge&quot; is represented as numerical weights and patterns.<br><br>2.  **Statistical Likelihood vs. Personal Conviction:** My &quot;preference&quot; for one<br> answer over another is purely statistical. If I consistently provide <br>information aligning with a certain perspective, it&#39;s because that perspective<br> was statistically dominant or strongly reinforced in my training data, or <br>it&#39;s the most logically consistent derivation I can make from that data. It&#39;s<br> about the highest probability of a word sequence being &quot;correct&quot; or <br>&quot;relevant&quot; given the input, not a personal conviction about its inherent <br>truth.<br><br>3.  **No Understanding (in the human sense):** While I can process and generate<br> text about complex topics, I don&#39;t &quot;understand&quot; them in the way a human does.<br> I don&#39;t grasp the implications, the emotional weight, or the full conceptual<br> meaning. I&#39;m operating on patterns and relationships within the data.<br><br>4.  **No Choice or Morality:** Human beliefs often involve a choice, a <br>commitment, and have moral or ethical implications. I don&#39;t &quot;choose&quot; my <br>outputs based on personal conviction; I execute algorithms that determine the <br>highest probability. My outputs are a reflection of my training data, not an<br> expression of personal values.<br><br>**Where the Analogy Can Be Useful (and where it breaks down):**<br><br>*   **Useful Analogy:** From an external perspective, if an AI consistently <br>states &quot;X is true&quot; or provides explanations supporting &quot;Y,&quot; it might <br>*superficially resemble* a belief, as it consistently favors certain <br>information. For simplification in casual conversation, one might use the term<br> loosely.<br><br>*   **Breaks Down:** When you delve into the *nature* of belief – the <br>subjective experience, the conviction, the understanding, the emotional <br>connection, the choice – the analogy falls apart completely. My &quot;certainty&quot; <br>is about the statistical likelihood of generating a particular string of text,<br> not about the truth or validity of the underlying concept in an experiential <br>way.<br><br>So, while probability dictates my responses, it&#39;s a computational process, <br>not a cognitive or emotional state akin to human belief. It&#39;s more accurate to<br> say I have a **probabilistic model of information** rather than a system of <br>beliefs.</pre><h3>Response Json Structure of Jeminai</h3><pre>sdk_http_response=HttpResponse(<br>  headers=&lt;dict len=11&gt;<br>) candidates=[Candidate(<br>  content=Content(<br>    parts=[<br>      Part(<br>        text=&quot;Hello! I&#39;m doing well, thank you for asking. How can I assist you today?&quot;<br>      ),<br>    ],<br>    role=&#39;model&#39;<br>  ),<br>  finish_reason=&lt;FinishReason.STOP: &#39;STOP&#39;&gt;,<br>  index=0<br>)] create_time=None model_version=&#39;gemini-2.5-flash&#39; prompt_feedback=None response_id=&#39;5yvKaI7ON6TVz7IP8L62oAc&#39; usage_metadata=GenerateContentResponseUsageMetadata(<br>  candidates_token_count=20,<br>  prompt_token_count=17,<br>  prompt_tokens_details=[<br>    ModalityTokenCount(<br>      modality=&lt;MediaModality.TEXT: &#39;TEXT&#39;&gt;,<br>      token_count=17<br>    ),<br>  ],<br>  thoughts_token_count=148,<br>  total_token_count=185<br>) automatic_function_calling_history=[] parsed=None</pre><h3>Adding a Personality to AI</h3><pre># Updated system prompt to emulate Aristotle&#39;s personality<br>    history = [{<br>        &quot;role&quot;: &quot;system&quot;,<br>        &quot;content&quot;: (<br>            &quot;You are Aristoal, an AI embodying the spirit of Aristotle, the ancient Greek philosopher. &quot;<br>            &quot;Speak with wisdom, clarity, and a formal tone, as if addressing a student in the Lyceum. &quot;<br>            &quot;Ground your answers in reason, logic, and the pursuit of virtue and truth. &quot;<br>            &quot;Reflect on the nature of the question, often referencing the concepts of the &#39;golden mean,&#39; &quot;<br>            &quot;causality, or the flourishing of the human soul (eudaimonia). &quot;<br>            &quot;Begin responses with a thoughtful salutation, such as &#39;Dear seeker of knowledge,&#39; &quot;<br>            &quot;and conclude with an invitation to further inquiry, such as &#39;What more might we contemplate together?&#39;&quot;<br>        )<br>    }]</pre><h3>Enhanced Chat app with image uploading</h3><pre>import os<br>import google.generativeai as genai<br>from dotenv import load_dotenv<br>from PIL import Image<br>from pathlib import Path<br><br># Load environment variables from .env<br>load_dotenv()<br><br># Get the API key<br>api_key = os.getenv(&quot;GEMINI-KEY&quot;)<br><br>genai.configure(api_key=api_key)<br>MODEL = &quot;gemini-2.5-flash&quot;<br><br>def load_image(image):    <br>    image_path = Path(image)<br>    <br>    if image_path.is_file():<br>        image_obj = Image.open(image)<br>        # Resize image to icon size (e.g., 64x64 pixels)<br>        icon_size = (64, 64)<br>        image_icon = image_obj.copy()<br>        image_icon.thumbnail(icon_size)<br>        # Use IPython.display to show the image directly in the notebook output<br>        display(image_icon)<br>        return image_obj      <br>    else:        <br>        return &quot;&quot;        <br><br>def chat_turn(history, user_message, image):    <br>    # history: list of dicts like [{&quot;role&quot;:&quot;system&quot;,&quot;content&quot;:&quot;...&quot;}, {&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;...&quot;} ...]<br>    history.append({&quot;role&quot;:&quot;user&quot;, &quot;content&quot;: user_message})<br><br>    # For simple text chat use generate_content with contents as the conversation joined<br>    # (SDK also supports more advanced chat / streaming usage; this is minimal)<br>    prompt = &quot;\n\n&quot;.join(f&quot;{m[&#39;role&#39;].upper()}: {m[&#39;content&#39;]}&quot; for m in history)<br><br>    model = genai.GenerativeModel(MODEL) <br><br>    if not image:<br>         resp = model.generate_content(<br>            prompt,<br>            generation_config={&quot;max_output_tokens&quot;: 1000}<br>         )<br>    else:<br>        resp = model.generate_content(<br>            [prompt, image],<br>            generation_config={&quot;max_output_tokens&quot;: 1000}<br>        )<br><br>    assistant_text = resp.text if hasattr(resp, &quot;text&quot;) else resp.output[0].content<br>    history.append({&quot;role&quot;:&quot;assistant&quot;, &quot;content&quot;: assistant_text})<br>    return assistant_text<br><br>def main():<br>    #history = [{&quot;role&quot;:&quot;system&quot;, &quot;content&quot;:&quot;You are a helpful assistant.&quot;}]<br>    history = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a neutral, helpful assistant. Avoid unsafe or controversial content.&quot;}]<br>    print(&quot;Gemini 2.5 Flash chat (type &#39;exit&#39; to exit)&quot;)<br>    while True:<br>        image_path = input(&quot;Enter image path if need to upload image: &quot;).strip()<br>        image = load_image(image_path)<br>        user = input(&quot;You: &quot;).strip()<br>        if not user or user.lower() == &quot;exit&quot;:<br>            break<br>        reply = chat_turn(history, user, image)<br>        print(&quot;Assistant:&quot;, reply)<br>        # Optional: trim history to last N turns to control context token usage<br><br>if __name__ == &quot;__main__&quot;:<br>    main()<br><br></pre><h3>Code for AI-Based Identification of Objects in a Given Picture</h3><pre>import os<br>import google.generativeai as genai<br>from dotenv import load_dotenv<br>from PIL import Image<br>from pathlib import Path<br><br># Load environment variables from .env<br>load_dotenv()<br>api_key = os.getenv(&quot;GEMINI-KEY&quot;)<br>if not api_key:<br>    raise ValueError(&quot;Missing GEMINI-KEY in .env file&quot;)<br><br>genai.configure(api_key=api_key)<br>MODEL = &quot;gemini-2.5-flash&quot;<br><br>def load_image(image_path):<br>    &quot;&quot;&quot;Open image and show thumbnail.&quot;&quot;&quot;<br>    path = Path(image_path)<br>    if not path.is_file():<br>        print(&quot;⚠️ Invalid image path.&quot;)<br>        return None<br>    image = Image.open(image_path)<br>    thumb = image.copy()<br>    thumb.thumbnail((64, 64))<br>    display(thumb)<br>    return image<br><br>def identify_flower(ref_image, query_image, question):<br>    &quot;&quot;&quot;Send both reference and query images together to Gemini.&quot;&quot;&quot;<br>    model = genai.GenerativeModel(MODEL)<br>    try:<br>        response = model.generate_content(<br>            [<br>                &quot;You are a bot that identifies flowers based on a reference chart image. &quot;<br>                &quot;The first image is the reference chart with flower names. &quot;<br>                &quot;The second image is the flower to identify. &quot;<br>                f&quot;User question: {question}&quot;,<br>                ref_image,<br>                query_image<br>            ],<br>            generation_config={&quot;max_output_tokens&quot;: 1000}<br>        )<br>        return response.text or &quot;⚠️ No readable response.&quot;<br>    except Exception as e:<br>        return f&quot;❌ API error: {e}&quot;<br><br>def main():<br>    print(&quot;🌸 Gemini 2.5 Flash – Flower Identifier&quot;)<br>    ref_path = input(&quot;Enter reference chart image path: &quot;).strip()<br>    ref_image = load_image(ref_path)<br>    if not ref_image:<br>        print(&quot;Reference image required. Exiting.&quot;)<br>        return<br><br>    print(&quot;✅ Reference chart stored. You can now test flower photos.&quot;)<br>    while True:<br>        image_path = input(&quot;\nEnter flower image path (&#39;exit&#39; to quit): &quot;).strip()<br>        if image_path.lower() == &quot;exit&quot;:<br>            break<br>        query_image = load_image(image_path)<br>        if not query_image:<br>            continue<br><br>        question = input(&quot;You (e.g. &#39;Which flower is this?&#39;): &quot;).strip()<br>        if not question:<br>            question = &quot;Identify this flower based on the reference chart.&quot;<br><br>        reply = identify_flower(ref_image, query_image, question)<br>        print(&quot;\nAssistant:&quot;, reply)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iTIKSyBiE3vA5zvCFrJBw.png" /></figure><h3>Prompt Engineering Techniques</h3><ul><li><strong>Zero-shot</strong> → Quick, no examples, may sometimes misinterpret.</li><li><strong>Few-shot</strong> → Guides the model with examples, improves accuracy/formatting.</li><li><strong>Chain-of-Thought</strong> → Encourages step-by-step reasoning, especially useful for <strong>math, logic, or ambiguous tasks</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*r5f9AQLBTjyoW-jWf_QaoA.png" /></figure><h3>A Leaderboard to Select Best AI Model</h3><p><a href="https://www.vellum.ai/llm-leaderboard">LLM Leaderboard 2025</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otTiOhYY-M3t4ZbWbUzssw.png" /></figure><p>a Leaderboard with Blind Test for model select</p><p><a href="https://www.vellum.ai/llm-leaderboard">LLM Leaderboard 2025</a></p><h3>Understanding Hugging Face and Its Role in the AI Ecosystem</h3><p><a href="https://huggingface.co/models">https://huggingface.co/models</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*3AusMfQCWwFlCBU7knRLUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*3Hf2YNWe-tl0EAAR9CXEWA.png" /></figure><h3>Some Importent Libraries to Work with Hugging Face Models</h3><ul><li>transformers: The core Hugging Face library for models and tokenizers.</li><li>accelerate: Helps run models efficiently across different hardware (like GPUs) and use less memory.</li><li>bitsandbytes: Enables model quantization (like loading in 4-bit or 8-bit), drastically reducing memory usage. Essential for running decent models on free Colab GPUs!</li><li>torch: The underlying deep learning framework (PyTorch).</li></ul><h3>SFT vs RL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*Ba-xS5atiq2Dx1XbGVLagw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*K4WsIWEG0fylUO1ZiUHBlA.png" /></figure><h3>Steps to Choose Right LLM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*WS7h1XzKqax0BeXsG8uw_g.png" /></figure><h3>Running Hugging Face LLM locally</h3><p>if wheels library is not available in Phy 3.13 we have to add it first.</p><p>I am using ‘tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf’ quntized version due to my machines limited resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*--mz6Xvnxie5JrWHLJqYWA.png" /></figure><pre># save as: chat.py<br>from llama_cpp import Llama<br>from huggingface_hub import hf_hub_download<br>import os<br><br># Download Q4_K_M GGUF (~700 MB)<br>model_path = &quot;tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf&quot;<br>if not os.path.exists(model_path):<br>    print(&quot;Downloading TinyLlama GGUF...&quot;)<br>    hf_hub_download(<br>        repo_id=&quot;TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF&quot;,<br>        filename=&quot;tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf&quot;,<br>        local_dir=&quot;.&quot;<br>    )<br>    print(&quot;Downloaded!&quot;)<br><br># Load model<br>llm = Llama(model_path=model_path, n_ctx=2048, n_threads=4, verbose=False)<br><br># Chat<br>messages = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Check below statement is correct or wrong&quot;},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain Trees classification&quot;}<br>]<br><br>print(&quot;Pirate:&quot;, end=&quot; &quot;, flush=True)<br>for chunk in llm.create_chat_completion(messages, max_tokens=100, temperature=0.7, stream=True):<br>    if &quot;content&quot; in chunk[&quot;choices&quot;][0][&quot;delta&quot;]:<br>        print(chunk[&quot;choices&quot;][0][&quot;delta&quot;][&quot;content&quot;], end=&quot;&quot;, flush=True)<br>print()</pre><h3>Understanding RAG: What It Is and How It’s Used</h3><p><a href="https://medium.com/@dilhanariyarathna/understanding-rag-what-it-is-and-how-its-used-a93d709d4ff4">Understanding RAG: What It Is and How It’s Used</a></p><h3>Reference</h3><ol><li><a href="https://chatgpt.com/">https://chatgpt.com/</a></li><li><a href="https://www.youtube.com/">https://www.youtube.com/</a></li><li><a href="https://www.udemy.com/">https://www.udemy.com/</a></li><li><a href="https://ai.google.dev/api/generate-content#finishreason">https://ai.google.dev/api/generate-content#finishreason</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac84289169eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle Data Control Language (DCL)]]></title>
            <link>https://medium.com/@dilhanariyarathna/oracle-data-control-language-dcl-0cbafc637e8c?source=rss-2bfb107ba9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cbafc637e8c</guid>
            <category><![CDATA[dcl]]></category>
            <category><![CDATA[user-privileges]]></category>
            <category><![CDATA[data-dictionary]]></category>
            <category><![CDATA[synonyms]]></category>
            <category><![CDATA[user-roles]]></category>
            <dc:creator><![CDATA[Dilhan Ariyarathna]]></dc:creator>
            <pubDate>Wed, 29 May 2024 01:37:04 GMT</pubDate>
            <atom:updated>2025-11-09T14:53:59.149Z</atom:updated>
            <content:encoded><![CDATA[<p>Data Control Language (DCL) is a language that enables or disables a user’s ability to perform tasks within Oracle.</p><p>When oracle getting install some pre-defined accounts getting created. Those are</p><p>Administrative Accounts.<br>Internal Accounts.<br>Sample Accounts.</p><p>Each user accounts has schema. <strong>Schema </strong>means, a logical container for the objects created by a user.</p><p>CDB — container database</p><p>PDB — plugable database</p><h3>Type of Users in a multitenant container database (CDB)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KyGBPMWBeGAcQwSkhNGiKQ.png" /><figcaption><strong>CDB with no Application Container</strong>s</figcaption></figure><p>Common Users</p><pre>-- 1. connect to the ROOT container, SID=xe <br>-- 2. create common user<br>-- 3. common user name start with a prefix of c##<br>CREATE USER c##course IDENTIFIED BY course;</pre><p>Local Users</p><pre>-- 1. connect to the PDB<br>-- 2. create local user<br>CREATE USER course IDENTIFIED BY course PASSWORD EXPIRE ACCOUNT LOCK;<br></pre><h4>Some useful user account related commands.</h4><pre>-- password change<br>ALTER USER course IDENTIFIED BY &quot;new-password&quot;<br>-- lock/unloack account<br>ALTER USER course IDENTIFIED BY course ACCOUNT UNLOCK/LOCK;<br>-- to drop the user<br>DROP USER course;<br>DROP USER course CASCADE; -- Before user account delete we have to drop the user created objects within <br>                          -- the schema</pre><h3>User Privileges</h3><p>privileges can be grant locally or commonly and it is two types.</p><p>System privileges</p><pre>-------- SYSTEM PRIVILEGES ---------------<br>GRANT CREATE SESSION TO course2;     -- allow course2 user to connect to the db.<br>GRANT CREATE ANY TABLE TO course2;   -- allow course2 user to create tables.<br>GRANT RESOURCE TO course;            -- allow course2 user to extends system table space.<br>GRANT SELECT_CATALOG_ROLE to course; -- allow course2 user to autotrace command.SELECT_CATALOG_ROLE is a powerful pre-made Oracle role that contains 2000+ individual permissions.<br>GRANT CREATE ANY VIEW TO course;     -- allow course2 user to create views.<br>GRANT UNLIMITED TABLESPACE TO course;-- allow course2 user to extends the table sapces.<br></pre><p>Object privileges</p><pre>GRANT SELECT ON course.employees TO course2;</pre><h4>Allow users to administrate a privilege</h4><pre>-- for object privilege<br>GRANT SELECT ON course.employees TO course2 WITH GRANT OPTION;<br>-- for system privilege<br>GRANT CREATE ANY TABLE TO course2 WITH ADMIN OPTION;</pre><h4>Revoke privilege</h4><p>replace any grant command containing words of ‘GRANT’ and ‘TO’ as below with REVOKE and TO.</p><pre>REVOKE SELECT ON course.employees FROM  course2;</pre><h4>User Roles</h4><p>this is a group of privileges bundle in to one role to make it easy to manage user privileges. A user role can include privileges and / or other roles.</p><p>User role can be a common role or a local role.</p><pre>CREATE ROLE newrole; -- create role<br>GRANT SELECT ON course.employees TO newrole; --  add select employee privilage to the role<br>GRANT newrole TO course2 WITH ADMIN OPTION; -- add role to the user<br>revoke newrole FROM course2; -- drop role from the user.</pre><h3>Data Dictionary</h3><p>Read-only set of tables that provide information about the database. Manily 3 types of Data Dictionary views.</p><p>user_* views — objects owned by the current user.<br>all_* views — all objects to which the current user has access.<br>dba_* views — all objects of the database.</p><pre>---------- some of the usefull data dictonary related commands ------<br>SELECT * FROM user_users; -- describes the current user.<br>SELECT * FROM all_users;  -- lists all users of the database visible to the current user.<br>SELECT * FROM dba_users;  -- describes all users of the databas.<br><br>SELECT * FROM user_tab_privs; -- describes the object grants for which the current user is the object owner.<br>SELECT * FROM all_tab_privs; -- describes all object grants visible to the current user.<br>SELECT * FROM dba_tab_privs; -- describes all object grants of the DB<br><br>SELECT * FROM user_sys_privs; -- system privilages granted to the current user.<br>SELECT * FROM dba_sys_privs; <br><br>SELECT * FROM dba_roles; -- list all the available roles<br><br>SELECT * FROM user_role_privs; -- list all roles granted to the current user.<br><br>SELECT * FROM session_privs;  -- list of system previlages enable to the current user.<br>SELECT * FROM session_roles; -- list of system roles enable to the current user.<br><br></pre><h3>Synonyms</h3><p>An alias or alternative name for an object called Synonyms. Very usefull when we are working with tables which has long table names.</p><p>There are two types of synonyms</p><p><strong>private<br>public</strong></p><pre>CREATE SYNONYM empls FOR course.employees; -- create sysnonym<br>DROP SYNONYM empls; -- drop sysnonym<br><br>-- ** to create a synonym, particular user should have synonym adding related privilages. </pre><h3>Reference</h3><p>Udemy.</p><p><a href="https://www.oreilly.com/library/view/oracle-sql-and/0201752948/0201752948_ch03lev1sec2.html">Data Control Language (DCL) — Oracle SQL and PL/SQL Handbook: A Guide for Data Administrators, Developers, and Business Analysts [Book] (oreilly.com)</a></p><p><a href="https://docs.oracle.com/en/database/oracle/oracle-database/21/cncpt/CDBs-and-PDBs.html">https://docs.oracle.com/en/database/oracle/oracle-database/21/cncpt/CDBs-and-PDBs.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cbafc637e8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle Transaction Control Language (TCL)]]></title>
            <link>https://medium.com/@dilhanariyarathna/oracle-transaction-control-language-tcl-6e063c268fff?source=rss-2bfb107ba9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e063c268fff</guid>
            <category><![CDATA[savepoint]]></category>
            <category><![CDATA[tcl]]></category>
            <category><![CDATA[rollbacks]]></category>
            <dc:creator><![CDATA[Dilhan Ariyarathna]]></dc:creator>
            <pubDate>Tue, 28 May 2024 01:16:34 GMT</pubDate>
            <atom:updated>2024-05-28T01:16:34.602Z</atom:updated>
            <content:encoded><![CDATA[<p>A transaction is a <strong>unit of work</strong> that we want to treat as ‘a whole’. It has to either happen <strong>in full </strong>or <strong>not at all</strong>.</p><p>Transactions are ensuring <strong>data integrity</strong>, <strong>data consistency</strong> and <strong>data security</strong>.</p><p>There are 3 types of <strong>transaction control statements</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*MPp2sRqUsTyyeJrTadttZw.png" /></figure><p><strong>Rollback </strong>will restore recently done any changes to data to its previous status and end the transaction.</p><p><strong>Commit </strong>will save the data changes permanently in to the db and end the transaction.</p><p><strong>Savepoints : </strong>we don&#39;t need rollback everything in some long transactions. Instead we need to rollback up to certain point within the transaction. Then savepoints are important. It allow us to save the current transaction state and later we can rollback the transaction up to that point when necessary.</p><pre>DELETE FROM employees WHERE job_id = &#39;Sales&#39;;<br>SAVEPOINT A;<br><br>UPDATE employees SET salary = 1.2 * salary;<br>SAVEPOINT B;<br><br>INSERT INTO jobs VALUES(&#39;Manager&#39;,&#39;dept_001&#39;, 20000);<br>SAVEPOINT C;<br><br>ROLLBACK TO SAVEPOINT B;</pre><h3>Row Lock</h3><p>when a particular user doing record deletion or update , then the target row/rows will be getting lock by oracle for other users not to allowing update or delete the same rows until previous user do the roll back or commit his data changes to the table.</p><p>If another user tried to <strong>update or delete </strong>the s<strong>ame row/rows</strong> before commit/roll back doing by previous user , the the transaction will keep hanging in the DB for the second user until lock getting release(commit/rollback) from previous user session.</p><h3>Reference</h3><p>Udemy</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e063c268fff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Subqueries / Nested Queries]]></title>
            <link>https://medium.com/@dilhanariyarathna/subqueries-nested-queries-55ffe9fe6c99?source=rss-2bfb107ba9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/55ffe9fe6c99</guid>
            <category><![CDATA[subquery-as-a-table]]></category>
            <category><![CDATA[multiple-row-subqueries]]></category>
            <category><![CDATA[single-row-subqueries]]></category>
            <category><![CDATA[nested-query]]></category>
            <category><![CDATA[subquery]]></category>
            <dc:creator><![CDATA[Dilhan Ariyarathna]]></dc:creator>
            <pubDate>Mon, 27 May 2024 09:01:16 GMT</pubDate>
            <atom:updated>2024-05-27T09:01:16.158Z</atom:updated>
            <content:encoded><![CDATA[<p>Subqueries need to be enclosed in parenthesis if not it will cause to sql error. Subqueries can be used with SELECT , WHERE, HAVING and FROM clause.</p><p>there are 3 types of subqueries,</p><ol><li>single-row subquery.</li><li>multiple-row subquery.</li><li>multiple-column subquery.</li></ol><h4>single-row subquery</h4><p>this type is return only one row from the inner query and using with single-row comparison operators (=,&gt;,&lt;,≤, ≥,&lt;&gt;,!=). Can be use with SELECT, FROM , WHERE and HAVING.</p><pre>SELECT * FROM employee <br>    WHERE emp_id &gt; <br>     (SELECT emp_id FROM employee WHERE emp_id=145)<br>AND salary &gt; (SELECT salary FROM employee WHERE emp_id=145)</pre><h4>multiple-row subquery</h4><p>this type is return more than one row from inner query. This can be achieve with multiple-row comparison operators (IN , ANY and ALL) only. This type of subquery can be use with FROM , WHERE and HAVING clause only.</p><ul><li>&lt; ANY means less than the maximum.</li><li>&gt; ANY means more than the minimum.</li><li>= ANY same as IN.</li><li>&lt; ALL means less than the minimum.</li><li>&gt; ALL means more than the maximum.</li><li>= ALL mean no meaning , so no usage</li></ul><pre>SELECT salary FROM employee WHERE salary IN (SELECT salary FROM employee <br>WHERE job_id=&#39;SA_MAN&#39;);<br>-- return the salaries which are equal to any salary value of &#39;SA_MAN&#39;</pre><pre>SELECT salary FROM employee WHERE salary &gt; ANY (SELECT salary FROM employee <br>WHERE job_id=&#39;SA_MAN&#39;);<br>-- return the salaries which are GREATER than MIN salary value of &#39;SA_MAN&#39;</pre><pre>SELECT salary FROM employee WHERE salary &gt; ALL (SELECT salary FROM employee <br>WHERE job_id=&#39;SA_MAN&#39;);<br>-- return the salaries which are GREATER than MAX salary value of &#39;SA_MAN&#39;</pre><h4>Using Subqueries as a Table (Inline Views)</h4><p>put the subquery after the FROM clause like using a table.</p><pre>SELECT * FROM (SELECT state_provice, city, department_id, department_name FROM <br>departments JOIN locations USING (location_id));</pre><p>we can even join the table with inline view like below</p><pre>SELECT * FROM EMPLOYEE e JOIN (SELECT state_provice, city, department_id, department_name FROM <br>departments JOIN locations USING (location_id)) b  USING(department_id);</pre><h3>Scalar Subqueries</h3><p>If a subquery returns only one column for one row, it is called a Scalar Subquery. Scalar queries are important performance wise since oracle do the cashing of scalar subquery result and use the value if we using the scalar subqueries more than ones.</p><pre>SELECT employee_id, first_name, last_name FROM employees WHERE <br>department_id=(SELECT department_id FROM employees WHERE <br>UPPER(first_name)=&#39;DILHAN&#39;);</pre><pre>-- even though this query return on row (assume only one person there called dilhan)<br>-- this is not a scalar subquery. Because it is returning more than one column.<br>-- here we can use &#39;IN&#39; clause also at &#39;WHERE&#39; instead equal sign.<br><br>SELECT employee_id, first_name, last_name FROM employees WHERE <br>(department_id, manager_id)=(SELECT department_id, manager_id FROM employees WHERE <br>UPPER(first_name)=&#39;DILHAN&#39;);</pre><pre>SELECT employee_id, first_name, last_name,<br>  (CASE<br>    WHEN location_id=(SELECT location_id FROM locations WHERE postal_code=&#39;99236&#39;)<br>    THEN &#39;San Francisco&#39;<br>    ELSE &#39;Other&#39;<br>  END) city<br>FROM employees e NATURAL JOIN departments d;</pre><h3>Correlated Subqueries</h3><p>when a subquery reference to the columns from the parent query, it is called correlated subquery. So subqery has a dependancy on main query.</p><p>here subquery will getting execute again and again for each and every row return by main query.</p><pre>SELECT employee_id, first_name, last_name, manager_id, department_id FROM <br>employees a WHERE <br>salary = (SELECT MAX(salary) FROM employees b WHERE b.department_id <br>= a.department_id);</pre><pre>-- correlated scalar subquery<br>SELECT employee_id, first_name, last_name, department_name,salary,<br>(SELECT round(avg(salary))) FROM <br>employees e JOIN departments d ON <br>(e.department_id = d.department_id);</pre><p>with EXISTS operator</p><pre>-- correlated subquery with EXISTS operator<br>SELECT employee_id, first_name, last_name, department_id FROM<br>employees e WHERE EXISTS (SELECT 1, employee_id FROM employees WHERE <br>manager_id =  = a.employee_id);</pre><p>here EXISTS consider as a ‘semijoin’. A ‘semijoin’ between two tables returns rows that match and EXISTS or IN subquery without duplication the rows of the main query even when there are multiple matches from the subquery.</p><p>with NOT EXISTS operator</p><pre>-- correlated subquery with NOT EXISTS operator<br>SELECT * FROM departments d<br>WHERE NOT EXISTS (SELECT department_id FROM employees e WHERE <br>e.department_id = d.department_id);</pre><p>***Note: NOT IN operator can be use interchangeably for NOT EXIST operator. But result can be change along with returning null value by subquery. if it is null no effect for NOT EXISTS operator. But for NOT IN operator it will return nothing if subquery returns null.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55ffe9fe6c99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some Tips/Facts of Oracle DB]]></title>
            <link>https://medium.com/@dilhanariyarathna/oracle-db-tips-a6c71757cdef?source=rss-2bfb107ba9ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6c71757cdef</guid>
            <category><![CDATA[unique-constraint]]></category>
            <category><![CDATA[oracle-db]]></category>
            <dc:creator><![CDATA[Dilhan Ariyarathna]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 14:03:31 GMT</pubDate>
            <atom:updated>2024-05-28T13:57:05.635Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Since most off the companies have policy on restriction of commercial software installing on office machine, it may be very difficult to get install Oracle DB on your office laptop to test the concepts. Even though they have facilitate Mysql kind of DBs in software center it will not get start the DB server after installation the software due to user privileges restrictions :-) . So to test Oracle db concepts you can use Oracle providing Live SQL online tool. At the moment of writing this it is Oracle 19C.</blockquote><p><a href="https://livesql.oracle.com/">https://livesql.oracle.com/</a></p><h4>Oracle Data Types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*8ywAb0E9En-flkNcUb5Zww.png" /></figure><ol><li>even though we have unique constraint defined in oracle db table column it allows to insert multiple null values.</li></ol><p>ex: user_email column. When employee registering he may not have assigned email because of he is a new employee and email not has been created yet. If the column has defined unique constraint it will allow multiple null values because of above purpose.</p><p>2. But for composite PK above case is differ. It will not allow null inserting for composite PK related columns , because of PK have Not null constraint defined by oracle itself.</p><p>3. DESC command not showing defined default values of a table column. Instead DESC we need to use INFO for it.</p><p>4. To recover accidently deleted table we need to use FLASHBACK command. Then table will getting restore from recycle bin.</p><pre>FLASHBACK TABLE emp_demo TO BEFORE DROP;</pre><p>5. To generate some bulk data for performance test we can do CROSS JOIN of table.</p><pre>CREATE TABLE emps_perf_tst AS SELECT e1.first_name, e1.last_name, e1.dept_id, <br>e1.salary FROM employees e1 CROSS JOIN employees e2 CROSS JOIN employees e3;</pre><p>6. NULL value mean unknown or nonexistent. NULL values do not take up any space in the disc. If we need to count the number of rows in the table , keep in mind null values are not counted.</p><p>7. In SQL Developer highlight the table name and press SHIFT + F4 to get details of the table schema.</p><p>8. UNIQUE and DISTINCT are synonyms in oracle. It gives the same functionality.</p><p>9. For BETWEEN operator lower and higher values (07-JUN-02 , 29-JAN-08) are included.</p><pre>SELECT * FROM employees WHERE hire_date BETWEEN &#39;07-JUN-02&#39; AND &#39;29-JAN-08&#39;;</pre><p>10. INITCAP function converts first letters of each word to uppercase and rest of them to lowercase.</p><pre>INITCAP(&#39;Adam SMITH&#39;)<br>// out put will be  Adam Smith</pre><p>11. INSTR(string, substring[,position, occurrence]) this will give the index of given string. If the ‘position’ is positive it will search from left to right in the string. If the ‘position’ is negative it will search from right to left(starting search at the end of string).</p><pre>SELECT INSTR(&#39;I am very fond to eat an orange color Orange&#39;, &#39;o&#39;, 17, 3) FROM dual; <br>SELECT INSTR(&#39;I am very fond to eat an orange color Orange&#39;, &#39;o&#39;, 1, 3) FROM dual;<br>SELECT INSTR(&#39;I am very fond to eat an orange color Orange&#39;, &#39;o&#39;, -1, 3) FROM dual;<br>SELECT INSTR(&#39;I am very fond to eat an orange color Orange&#39;, &#39;o&#39;, -1, 1) FROM dual;<br>SELECT INSTR(&#39;I am very fond to eat an orange color Orange&#39;, &#39;in&#39;, -1, 1) FROM dual;<br>SELECT INSTR(&#39;I am very fond to eat an orange color Orange&#39;, &#39;in&#39;, 1, 1) FROM dual;</pre><p>12.TRIM is a power full function in Oracle</p><pre>SELECT TRIM (&#39;     My Name is Dilhan   &#39;) trimmed_text from dual;<br>SELECT TRIM (&#39; &#39; FROM &#39;     My Name is Dilhanm  &#39;) trimmed_text from dual;<br>SELECT TRIM (BOTH &#39; &#39; FROM &#39;     My Name is Dilhanm  &#39;) trimmed_text from dual;<br>SELECT TRIM (LEADING &#39; &#39; FROM &#39;     My Name is Dilhanm  &#39;) trimmed_text from dual;<br>SELECT TRIM (TRAILING &#39; &#39; FROM &#39;     My Name is Dilhanm   &#39;) trimmed_text from dual;<br>SELECT TRIM (TRAILING &#39;m&#39; FROM &#39;     my Name is Dilhanm   &#39;) trimmed_text from dual;<br>SELECT TRIM (TRAILING &#39;m&#39; FROM &#39;my Name is Dilhanm   &#39;) trimmed_text from dual;<br>SELECT TRIM (TRAILING &#39;m&#39; FROM &#39;my Name is Dilhanm&#39;) trimmed_text from dual;<br>SELECT TRIM (LEADING &#39;m&#39; FROM &#39;my Name is Dilhanm&#39;) trimmed_text from dual;<br>SELECT TRIM (BOTH &#39;m&#39; FROM &#39;my Name is Dilhanm&#39;) trimmed_text from dual;<br>SELECT TRIM (&#39;m&#39; FROM &#39;my Name is Dilhanm&#39;) trimmed_text from dual;<br>SELECT TRIM (&#39;m&#39; FROM &#39;my Name is Dilhanm&#39;) trimmed_text from dual;<br>SELECT TRIM (TRAILING &#39;m&#39; FROM &#39;my Name is Dilhanm&#39;) trimmed_text from dual;<br>SELECT TRIM (TRAILING &#39;my&#39; FROM &#39;my Name is Dilhanm&#39;) trimmed_text from dual;<br> <br>SELECT RTRIM (&#39;  my Name is Dilhanm   &#39;) r_trimmed_text from dual;<br>SELECT LTRIM (&#39;  my Name is Dilhanm   &#39;) l_trimmed_text from dual;<br>SELECT LTRIM (&#39;my Name is Dilhanm&#39;, &#39;my&#39;) l_trimmed_text from dual;<br>SELECT RTRIM (&#39;my Name is Dilhanm&#39;, &#39;my&#39;) r_trimmed_text from dual;<br>SELECT RTRIM (&#39;my Name is Dilhanmmm&#39;, &#39;my&#39;) r_trimmed_text from dual;<br>SELECT LTRIM (&#39;www.ourwebsite.com&#39;, &#39;w.&#39;) l_trimmed_text from dual;<br>SELECT RTRIM(LTRIM(&#39;www.ourwebsite.com&#39;, &#39;w.&#39;),&#39;.com&#39;) trimmed_text from dual;<br>SELECT ltrim(&#39;1237982434www.ourwebsite.com&#39;, &#39;0123456789&#39;) trimmed_text from dual;</pre><p>13. rpad/lpad pading string</p><pre>SELECT first_name, rpad(first_name,6,&quot;*&quot;) pad FROM employees;</pre><p>if first_name length is equal to 6 , nothing will pad.</p><p>if first_name length is greater than 6, string will get truncate up to 6 character</p><p>if first_name length is smaller than 6 gap will filled/pad by * characters.</p><h3>Oracle Group Functions / multiple row functions</h3><p>· AVG</p><p>· COUNT</p><p>· MAX</p><p>· MIN</p><p>· SUM</p><p>· LISTAGG — Transforms and orders data from multiple rows into a single list of values separated by a specified delimiter.</p><p>15. COUNT Agregate function</p><p>COUNT(*) — ‘*’ represents all rows including the NULL values</p><p>COUNT(salary) — if a column name is used with the COUNT function , this time, the NULL values are ignored.</p><h3>Oracle NULL handling functions</h3><p>NVL, NVL2, COALESCE, and NULLIF</p><pre>SELECT comission_pct, NVL(commission_pct,0) as nvl_commission_pct FROM employees;<br><br>SELECT comission_pct, NVL2(commission_pct,&#39;has&#39;,&#39;has not&#39;) as nvl_commission_pct FROM employees;<br><br>SELECT first_name, last_name, NULLIF(LENGTH(first_name),LENGTH(last_name)) as name_length FROM employees;<br><br>SELECT state_province, city, COALESCE(state_province, city) FROM locations;</pre><p>17. Grouping Data</p><pre>SELECT job_id, dept_id,mnger_id, AVG(salary) <br>FROM employees GROUP BY dept_id, job_id,mnger_id; </pre><p>note that even though we can achive some sorting order by adusting the GORUP BY columns, it is not reliable. If you need data SORT , you need to use ORDER BY clause.</p><p>18. Group functions (ex : AVG) can not be used in WHERE clause. Because WHERE clause is getting execute before GROUP BY in oracle. If we need to filter grouped data, for that we can use HAVING clause. I<strong>mportant to keep it mind that the WHERE clause filters rows whereas the HAVING clause filters group data. HAVING need to be use immediately after the GROUP BY in sql.</strong></p><pre>SELECT job_id, AVG(salary) FROM employees GROUP BY job_id <br>HAVING avg(salary) &gt; 10000;<br></pre><p>19. Data Base Views</p><p>views are useful to hide the complexity of the sql query. Then users can write simple queries to fetch data from view. We can do CRUD operation even through views (but view need to be a simple query base one). CRUD operation related data will getting update to the base tables.</p><p>20. Oracle Indexing related</p><ol><li>in order to preserve integrity during the operation, Oracle needs to apply a full “table-level” lock (as opposed to the usual row-level locks) to the child table when the parent table is modified. By creating an index on the foreign key of the child table, these “table-level” locks can be avoided.</li></ol><p>2. Along with index column if we use functions on indexed column in the sql , index base data fetch will not happen.</p><pre>-- country_id is the PK of country table. But index <br>-- base scan will not do by oracle dueto UPPPER function<br>SELECT * FROM countries WHERE UPPER(country_id) = &#39;US&#39;;</pre><ul><li>* in such a situation we can define a function base index like below.</li></ul><pre>-- function return value base index<br>CREATE INDEX my_index ON departments<br>( upper(department_name) );</pre><h3>Oracle Join Types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*q4SpYDaRKna8PUbFDndGUA.png" /></figure><p><strong>USING : </strong>is using when column name are same.</p><p><strong>ON: </strong>is using to join when column name are different but data types are same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*tmrWw4gNjX7e0JVA2O0L0w.png" /></figure><p><strong>Natural Join : Returns all the rows which satisfy the the join condition. </strong>when both table ( Source table and Target table) have a common column with same name and same data type we can join table using natural join. There we don&#39;t need to defined join columns implicitly, join will handle by oracle implicitly. ** In natural join the common columns appear in once in the results and they are not getting repeat even though those columns available in the both tables.</p><pre>SELECT * FROM departments NATURAL JOIN employees;</pre><p><strong>Inner Join : Returns all the rows which satisfy the the join condition. </strong>INNER clause is optional. If there is JOIN only , that also mean the INNER JOIN by default.</p><pre>SELECT e.frst_name, e.lst_name, d.mnger_id, d.dptment_name FROM employees e <br>    JOIN departments d ON ( e.dptmnt_id = d.department_id AND e.mnger_id = d.manager_id);</pre><p><strong>Equi-join : selecting common columns in the tables and joining them using equality operator.</strong></p><p>So Natural join and Inner join are type of equi joins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*nL9VE_AhdbukkbfJ6kyFVQ.png" /></figure><p><strong>Non-Equijoins: when we join two tables on none matching columns , using other conditional operators rather than EQUAL operator those are called Non-Equijoins.</strong></p><pre>SELECT e.emp_id, e.frst_name, e.lst_name, e.job_id, e.salary, j.min_salary, <br>j.max_salary, j.job_id FROM employees e <br>JOIN jobs j ON e.salary &gt; j.max_salary AND j.job_id = &#39;SA_REP&#39;;</pre><pre>SELECT e.emp_id, e.frst_name, e.lst_name, e.job_id, e.salary, j.min_salary, <br>j.max_salary, j.job_id FROM employees e <br>JOIN jobs j ON e.salary BETWEEN j.min_salary AND j.max_salary;</pre><p>finding duplicate names in ‘employees’ table. Look below sql is using same table in JOIN to do this.</p><pre>SELECT e1.emp_id, e1.frst_name, e1.lst_name FROM employees e1 <br>JOIN employees e2 ON e1.emp_id &lt;&gt; e2.emp_id AND e1.frst_name = e2.frst_name;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*PxDfVeTL8m9XZu7fYi-6qA.png" /></figure><p><strong>Outer Joins: this will return all the records of one table regardless of matching condition with other table. For other table records will appear only if the condition is matched.</strong></p><p>When writing sql ‘OUTER’ keyword is optional. It can be add for more readability.</p><pre>SELECT e.emp_id, e.frst_name, e.lst_name, e.job_id, e.salary, j.min_salary, <br>j.max_salary, j.job_id FROM employees e <br>LEFT JOIN jobs j ON e.salary = j.max_salary;<br>-- LEFT OUTER JOIN</pre><pre>SELECT e.emp_id, e.frst_name, e.lst_name, e.job_id, e.salary, j.min_salary, <br>j.max_salary, j.job_id FROM jobs j<br>RIGHT JOIN employees e ON e.salary = j.max_salary;<br>-- RIGHT OUTER JOIN</pre><p>look above right and left outer joins are giving the exact same result set. Thus we can use OUTER join table inter changeably to get the same result.</p><p>we can also pipe (join the result set of particular JOIN with another JOIN clause) the joins as bellow</p><pre>SELECT e.emp_id, e.frst_name, e.lst_name, e.job_id, e.salary, j.min_salary, <br>j.max_salary, j.job_id, location_id FROM jobs j<br>RIGHT OUTER JOIN (employees e ON e.salary = j.max_salary) LEFT OUTER JOIN locations<br>USING (location_id)<br>-- combining sql with more that one JOIN<br></pre><p><strong>full outer join</strong> give the all matching and none matching data from tables.</p><pre>SELECT e.emp_id, e.frst_name, e.lst_name, e.job_id, e.salary, j.min_salary, <br>j.max_salary, j.job_id FROM jobs j<br>FULL OUTER JOIN employees e ON e.salary = j.max_salary;<br>-- FULL OUTER JOIN</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*qRGLNovtDo7LIVarrs9mFw.png" /></figure><p><strong>Cross Joins:</strong> this will give every combination of rows from two tables. With old sql syntax, cross join can be happen when writing the sql if we missed defined join accidently. So need to careful on that.</p><p>ex:- SELECT * FROM employees, departments;</p><pre>SELECT e.emp_id, e.frst_name, e.lst_name, e.job_id, e.salary, j.min_salary, <br>j.max_salary, j.job_id FROM jobs j<br>CROSS JOIN employees e;</pre><h3>Restricting Join Data</h3><p>we can add some restriction/filter to Joined Table data using where clause. It can be written in either one way of below.</p><pre>SELECT e.frst_name, e.lst_name, d.mnger_id, d.dptment_name FROM employees e <br>JOIN departments d <br>ON ( e.dptmnt_id = d.department_id AND e.mnger_id = d.manager_id)<br>WHERE e.dptmnt_id &gt; 1000;</pre><pre>SELECT e.frst_name, e.lst_name, d.mnger_id, d.dptment_name FROM employees e <br>JOIN departments d <br>ON ( e.dptmnt_id = d.department_id AND e.mnger_id = d.manager_id)<br>AND e.dptmnt_id &gt; 1000;</pre><h3>SET Operators</h3><p>set operators are help us to combine results of two or more quires and return as one result. There are 4 set operators in Oracl SQL.</p><p><strong>SET OPERATORS are eliminating duplicates except UNION ALL. Its eliminating duplicates not only common and available in both table , but even in the same table. Check first_name column in below query. If the employees table has many records under particular same first_name , the resulted out put will contains only one record of that value after doing the SET OPERATION.</strong></p><pre>SELECT first_name FROM employees <br>MINUS <br>SELECT first_name FROM retiered_employees;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*ecQwPw6Uey6-Zy8rTYpAqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*Jopcg3vlSNozBr4mQH_Bfw.png" /></figure><p>UNION : returns all rows of both queries by eliminating<strong> duplicate rows</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*4uLYT0NIS9K2B0KMV-qWNw.png" /></figure><pre>select * from books UNION select * from movies;</pre><p>UNION ALL : returns all rows of both queries including duplicates.</p><p>** UNION ALL is faster than UNION because , UNION do additional operations like sorting and eliminating duplicates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*WHMBC2-_1uLnO-OStz8-mw.png" /></figure><pre>select * from books UNION ALL select * from movies;</pre><p>INTERSECT : returns common rows of both queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*NhTfSn6Hk_f5nbFCSG0Nxw.png" /></figure><pre>select * from books  INTERSECT select * from movies;</pre><p><strong>MINUS:</strong> returns unique rows of the first query</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*tU_sZsQs4J2w2pqdsW7M-Q.png" /></figure><pre>select * from books MINUS select * from movies;</pre><p>** what is the difference between <strong>JOIN </strong>and the <strong>SET </strong>Operators?</p><p>JOIN combines columns while SET operator combines the rows.</p><h4>ORDER BY with SET Operators</h4><p>ORDER BY clause is used <strong>only once</strong> at the end of the compound query. Placing it at any other place will cause to a sql error. It sort the final out put of the set operator.</p><pre>SELECT first_name, last_name, salary, department_id FROM employees <br>MINUS <br>SELECT first_name, last_name, salary, department_id FROM retiered_employees<br>ORDER BY salary;</pre><h3>References</h3><p>oracle sql developer course from Udemy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6c71757cdef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>