<?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 Atul Sutar on Medium]]></title>
        <description><![CDATA[Stories by Atul Sutar on Medium]]></description>
        <link>https://medium.com/@atul-sutar?source=rss-9079fe4063cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PQKEaJEmBY-_V-7QDsgTYA.png</url>
            <title>Stories by Atul Sutar on Medium</title>
            <link>https://medium.com/@atul-sutar?source=rss-9079fe4063cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:15:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atul-sutar/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[Building a Scalable AI Data Pipeline on Google Cloud]]></title>
            <link>https://atul-sutar.medium.com/building-a-scalable-ai-data-pipeline-on-google-cloud-021c752de9eb?source=rss-9079fe4063cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/021c752de9eb</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[google-cloud-sql]]></category>
            <category><![CDATA[google-pubsub]]></category>
            <dc:creator><![CDATA[Atul Sutar]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 06:25:51 GMT</pubDate>
            <atom:updated>2026-09-15T07:10:29.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqjKtz4mG2Vc7ndkzGc8bg.png" /></figure><p>Every organization today is collecting more data than ever before. The challenge is no longer just storing data, but processing it efficiently, enriching it with AI, and making it available for analytics. As data volume grows, a simple script or a monolithic application quickly becomes difficult to scale and maintain.</p><p>Recently, I worked on designing an event driven data pipeline that focuses on reliability, scalability, and automation. The goal was straightforward. As new Parquet files arrive, the system should automatically process them, enrich the data using AI, and make the results available in BigQuery for reporting and analytics.</p><p>This article walks through the architecture, the technologies involved, and the reasoning behind each design decision.</p><h3>The Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GszZ-9WiCiqSD4IyKV1VIQ.png" /><figcaption>AI summarization Batch Job Image</figcaption></figure><p>The pipeline begins when a Parquet file is uploaded to a Google Cloud Storage bucket. Instead of polling the bucket continuously, Google Cloud Storage generates an Object Creation event as soon as a new file is uploaded.</p><p>That event is published to Cloud Pub/Sub, which acts as the messaging layer between the storage system and downstream services. The event contains metadata about the uploaded file, such as the bucket name, object path, and creation timestamp.</p><p>Rather than consuming Pub/Sub messages directly, I used a Kafka connector to publish the event into a Kafka topic. Kafka provides a durable and scalable event streaming platform, making it easier to integrate with downstream systems while allowing multiple consumers if the architecture grows in the future.</p><p>From Kafka, another connector writes the file metadata into a PostgreSQL database running on Cloud SQL. At this stage, only metadata is stored. The actual file remains safely stored in Cloud Storage.</p><p>This metadata table acts as the control layer for the processing application. Every uploaded file has a corresponding entry with its processing status, timestamps, and other operational information.</p><p>Once every day, a Kubernetes batch job starts processing the pending files. Instead of relying on a single application instance, multiple worker pods can run simultaneously, allowing the workload to be distributed across the cluster.</p><p>Each worker reads a batch of pending files from PostgreSQL, downloads the corresponding Parquet files from Cloud Storage, performs the required transformations, and invokes AI services to enrich the data.</p><p>Depending on the business use case, the AI layer can classify records, extract structured information, summarize content, or generate additional insights from the raw data.</p><p>After processing is complete, the enriched data is loaded into BigQuery, where it becomes available for analytics, dashboards, and reporting.</p><h3>End to End Flow</h3><p>The overall flow looks like this.</p><ol><li>A Parquet file is uploaded to Google Cloud Storage.</li></ol><p>2. Google Cloud Storage generates an Object Creation event.</p><p>3. Cloud Pub/Sub receives the event containing the file metadata.</p><p>4. A Kafka connector publishes the event into a Kafka topic.</p><p>5. A Kafka sink connector stores the metadata in PostgreSQL running on Cloud SQL.</p><p>6. A scheduled Kubernetes batch job queries PostgreSQL for files that are waiting to be processed.</p><p>7. Multiple worker pods process the files in parallel.</p><p>8. Each worker invokes AI services to enrich the data.</p><p>9. The processed results are loaded into BigQuery.</p><p>10. Business users and analysts can query the data directly from BigQuery.</p><h3>Why Use PostgreSQL as a Metadata Store</h3><p>One question that often comes up is why introduce PostgreSQL instead of processing files directly from Pub/Sub.</p><p>The answer is operational visibility.</p><p>By maintaining a metadata table, the application always knows which files are pending, currently processing, successfully completed, or failed. It also becomes much easier to retry failed files without replaying the entire messaging pipeline.</p><p>This design also provides better observability since every file has a processing history stored in a relational database.</p><h3>Why Use Kubernetes</h3><p>Processing a handful of files every day can be handled by a single application, but processing hundreds of thousands of records requires a different approach.</p><p>Running the processing application on Kubernetes provides horizontal scalability. As the workload increases, additional worker pods can be created to process multiple files simultaneously.</p><p>This significantly reduces processing time while keeping the architecture resilient. If one pod fails, Kubernetes automatically recreates it, allowing the remaining workers to continue processing without affecting the overall pipeline.</p><h3>AI Processing at Scale</h3><p>The AI layer is one of the most important parts of the pipeline.</p><p>After reading the data from each Parquet file, the application sends requests to an AI model for enrichment. Since every file may contain thousands of records, the application processes them efficiently using parallel execution while respecting API rate limits.</p><p>The enriched output is then transformed into an analytics friendly format before being written to BigQuery.</p><p>Separating AI processing from data ingestion keeps the architecture modular and allows the AI component to evolve independently as newer models become available.</p><h3>Why BigQuery</h3><p>BigQuery is the final destination for the processed data because it is designed for large scale analytics.</p><p>Once the enriched data is available in BigQuery, analysts can run SQL queries, build dashboards, create reports, or even train machine learning models without worrying about infrastructure management.</p><p>It becomes the single source of truth for downstream analytics.</p><h3>Final Thoughts</h3><p>This architecture combines event driven design, scalable processing, and AI enrichment into a single workflow.</p><p>Google Cloud Storage handles file ingestion, Pub/Sub manages event delivery, Kafka provides durable event streaming, PostgreSQL tracks processing status, Kubernetes enables scalable batch processing, AI adds intelligence to the data, and BigQuery serves as the analytics platform.</p><p>The biggest advantage of this design is that each component has a clear responsibility. Storage handles files, messaging handles events, PostgreSQL tracks processing, Kubernetes performs computation, AI enriches the data, and BigQuery powers analytics. This separation makes the system easier to scale, monitor, and maintain as data volumes continue to grow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=021c752de9eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch Processing with OpenAI APIs]]></title>
            <link>https://atul-sutar.medium.com/batch-processing-with-openai-apis-8a26279ac5d1?source=rss-9079fe4063cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a26279ac5d1</guid>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Atul Sutar]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 13:42:09 GMT</pubDate>
            <atom:updated>2026-09-15T07:09:44.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FPnkbyv3SiutvJecni9Vw.png" /></figure><p>If you’re running large-scale LLM jobs and paying full price for synchronous calls, you’re leaving 50% of your budget on the table.</p><h4><strong>The Problem</strong></h4><p>You’ve got 10,000 rows of data. Customer feedback to classify, documents to summarize, a nightly eval pipeline. The naive approach is looping through everything and calling the API one by one. It works. But it’s slow, fragile, and expensive.</p><h4>Enter the Batch API</h4><p>OpenAI’s Batch API lets you fire off thousands of requests asynchronously at <strong><em>half the price</em></strong> of regular API calls. The trade-off? Results take up to 24 hours.</p><p>For anything non-real-time like evals, data enrichment, or offline inference, this is a no-brainer.</p><p>The flow is simple: pack requests into a <strong><em>.jsonl</em></strong> file, upload it, submit the job, come back later and grab your results.</p><h4>The Code</h4><p>Each line in <strong><em>batch_data.jsonl</em></strong> is one independent request:</p><pre>{&quot;custom_id&quot;: &quot;req-1&quot;, &quot;method&quot;: &quot;POST&quot;, &quot;url&quot;: &quot;/v1/chat/completions&quot;, &quot;body&quot;: {&quot;model&quot;: &quot;gpt-4o-mini&quot;, &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Summarize this: …&quot;}]}}</pre><p>The <strong><em>custom_id</em></strong> maps results back to your original data. Don’t skip it.</p><pre>from dotenv import load_dotenv<br>from openai import OpenAI<br>import time<br><br>load_dotenv(override=True)<br><br><br>client = OpenAI()<br><br>print(&quot;Creating batch input file...&quot;)<br>batch_input_file = client.files.create(<br>    file=open(&quot;batch_data.jsonl&quot;, &quot;rb&quot;), purpose=&quot;batch&quot;<br>)<br><br>print(&quot;Batch input file created: &quot;, batch_input_file.id)<br><br><br>print(&quot;Creating batch...&quot;)<br>batch_response = client.batches.create(<br>    input_file_id=batch_input_file.id,<br>    endpoint=&quot;/v1/chat/completions&quot;,<br>    completion_window=&quot;24h&quot;,<br>    metadata={&quot;description&quot;: &quot;nightly eval job&quot;},<br>)<br><br>print(&quot;Batch ID: &quot;, batch_response.id)<br>print(&quot;Batch Status: &quot;, batch_response.status)<br><br><br>print(&quot;Getting batch...&quot;)<br>batch = client.batches.retrieve(batch_response.id)<br><br>while batch_response.status != &quot;completed&quot;:<br>    time.sleep(1)<br>    batch_response = client.batches.retrieve(batch_response.id)<br>    print(&quot;Batch Status: &quot;, batch_response.status, end=&quot;\r&quot;, flush=True)<br><br>print(&quot;Getting file content...&quot;)<br>file_response = client.files.content(batch_response.output_file_id)<br><br><br>with open(&quot;batch_data_results.jsonl&quot;, &quot;w&quot;) as f:<br>    f.write(file_response.text)</pre><p>25 lines. That’s it.</p><h4>When to Use It</h4><p>Use this for nightly evals, bulk classification, offline summarization, or embedding generation at scale. Skip it for anything user-facing or latency-sensitive. The 24h window is not negotiable.</p><h4>The Real Impact</h4><p>At scale, 50% off is not pocket change. But beyond cost, it pushes you toward better engineering. Async, decoupled, fault-tolerant. The batch mindset scales. The “call it and pray” loop doesn’t.</p><p>If you’re building data-heavy pipelines with OpenAI, make this your default for offline workloads.</p><p><strong><em>You can find the complete code here on </em></strong><a href="https://github.com/atul-sutar/openai-batch-api-poc"><strong><em>GitHub</em></strong></a></p><p><strong><em>Follow for more practical AI engineering content.</em></strong></p><p><strong><em>References:</em></strong></p><p><a href="https://developers.openai.com/api/docs/guides/batch">Batch API | OpenAI API</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a26279ac5d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Data Pipelines with GCP’s Managed Kafka and Pub/Sub Connectors]]></title>
            <link>https://atul-sutar.medium.com/building-data-pipelines-with-gcps-managed-kafka-and-pub-sub-connectors-bff7831836de?source=rss-9079fe4063cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bff7831836de</guid>
            <category><![CDATA[gcp-managed-kafka]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Atul Sutar]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 18:07:17 GMT</pubDate>
            <atom:updated>2026-09-15T07:08:58.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tto4vHC0kyj66j9zkl16BA.png" /></figure><p>Hey everyone! Today I’m excited to walk you through one of Google Cloud’s powerful integrations: connecting Managed Service for Apache Kafka with Pub/Sub using source and sink connectors. This setup is perfect for building robust data pipelines that bridge Kafka’s streaming capabilities with Pub/Sub’s server-less messaging.</p><h3>What We’re Building Today</h3><p>We’ll create a complete data flow where messages can seamlessly move between Pub/Sub topics and Kafka topics in both directions. This is incredibly useful for hybrid architectures where you need to integrate Kafka-based applications with Google Cloud’s native services.</p><h3>Prerequisites and Environment Setup</h3><p>Before we dive into the implementation, let’s get our environment ready. This setup requires several moving pieces, but I’ll guide you through each step.</p><h3>Step 1: Service Account Configuration</h3><p>First, we need to create a service account with the right permissions. This account will handle authentication between our services.</p><p>Create a new service account and assign these roles:</p><ul><li>Kafka Client</li><li>Pub/Sub Subscriber</li><li>Pub/Sub Publisher</li><li>Pub/Sub Viewer</li></ul><p>Download the JSON key file — we’ll need this later for authentication. Keep this file secure as it provides access to your resources.</p><h3>Step 2: Google-Managed Service Account Permissions</h3><p>Google provides a service account that handles the connector operations behind the scenes. You’ll need to grant specific permissions to this account. The exact steps are documented in Google’s official guide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Cho9a4L3iPRimTNn5KH0w.png" /><figcaption>Service Account Setup</figcaption></figure><h3>Step 3: Setting Up Your Bastion Host</h3><p>Since Kafka endpoints operate behind Private Service Connect (PSC), we need a bastion host within the same VPC for interaction. I found this <a href="https://medium.com/google-cloud/local-development-with-google-cloud-managed-service-for-apache-kafka-8a50b2efb5ab">excellent Medium article</a> that walks through the setup process in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nn8oufE85ZNMfGJNOhjcA.png" /><figcaption>Bastion Host VM</figcaption></figure><h3>Step 4: Network Configuration</h3><p>Network setup is crucial for this integration. Ensure you have:</p><ul><li>A VPC network (create one if needed)</li><li>Proper firewall rules configured</li><li>Private Google Access enabled on your subnet</li></ul><p>This network configuration ensures seamless connectivity since Kafka endpoints sit behind Private Service Connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*S28IbTkzh1_j3CK817SMLg.png" /><figcaption>Network Configuration</figcaption></figure><h3>Step 5: Pub/Sub Resources</h3><p>Create your Pub/Sub infrastructure:</p><ul><li>Input topic with subscription</li><li>Output topic with subscription</li></ul><p>These will serve as the endpoints for our data flow testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*p2p7vKszN91-0zkJuvsLhA.png" /><figcaption>Pub Sub Topics</figcaption></figure><h3>Step 6: Kafka Cluster Setup</h3><p>Deploy your Managed Kafka cluster using the same network we configured earlier. For this demo, the default settings work fine, but you can adjust based on your specific requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Id1jR-88mxPi04CYUzJwNg.png" /><figcaption>Kafka Cluster</figcaption></figure><h3>Step 7: Kafka Topics</h3><p>Create input and output Kafka topics. The configuration depends on your use case, but Google provides excellent guidance on <a href="https://cloud.google.com/pubsub/docs/connect_kafka#message-conversion">message conversion patterns</a> between Pub/Sub and Kafka.</p><h3>Step 8: Connect Cluster and Connectors</h3><p>Finally, create your Connect cluster and set up both connectors:</p><ul><li>Pub/Sub source connector (Pub/Sub → Kafka)</li><li>Pub/Sub sink connector (Kafka → Pub/Sub)</li></ul><pre><br># Soucre Config<br>connector.class=com.google.pubsub.kafka.source.CloudPubSubSourceConnector<br>cps.project=project-id<br>cps.streamingPull.enabled=true<br>cps.subscription=kafka-publisher-sub<br>kafka.topic=kafka-input<br>key.converter=org.apache.kafka.connect.json.JsonConverter<br>name=pubsub-source-connector<br>tasks.max=3<br>value.converter=org.apache.kafka.connect.converters.ByteArrayConverter<br><br># Sink Config<br>connector.class=com.google.pubsub.kafka.sink.CloudPubSubSinkConnector<br>cps.project=project-id<br>cps.topic=kafka-subscriber<br>key.converter=org.apache.kafka.connect.converters.ByteArrayConverter<br>name=pubsub-sink-connector<br>tasks.max=3<br>topics=kafka-output<br>value.converter=org.apache.kafka.connect.converters.ByteArrayConverter</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xY6JSkFHHQF8IHlt8JX7Uw.png" /><figcaption>Kafka Connect Cluster</figcaption></figure><h3>Testing the Integration</h3><p>Now comes the exciting part — testing our pipeline!</p><p>SSH into your bastion VM and follow these steps:</p><ol><li><strong>Setup the Environment</strong>: Copy the test code from <a href="https://github.com/atul-sutar/gcp-kafka-basic">my repository</a> and install the required dependencies.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e598976077c4432fa0ce8a8600aa18a6/href">https://medium.com/media/e598976077c4432fa0ce8a8600aa18a6/href</a></iframe><ol><li><strong>Configure Authentication</strong>: Upload your service account JSON file and set the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to this file. Change variables as per your configuration in a script.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wp7m4jXi0NokEE3mUfIReg.png" /><figcaption>Add Required Details in Script</figcaption></figure><ol><li><strong>Run the Test Script</strong>: The script I’ve prepared will:</li></ol><pre>python main.py</pre><ul><li>Produce messages to the output topic</li><li>Wait to consume messages from the input topic</li><li>Validate the end-to-end flow</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNdhHpopSpiF9l3cNcyHlw.png" /><figcaption>Publish Message to Pub Sub Topic (Sends to Kafka Topic)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SY2z50SuRf0ocIQWofCZyw.png" /><figcaption>Script Output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3T38d2ol3VbVOvK0JYV_1g.png" /><figcaption>Pub-Sub Message Received from Kafka Topic</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYn17Hv48_l9TY8Zc5fN9Q.png" /><figcaption>Pub Sub Source Connector Logs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-qcMgHkod1VS_t9-57wvw.png" /><figcaption>Pub Sub Sink Connector Logs</figcaption></figure><h3>Monitoring and Troubleshooting</h3><h3>For Pub/Sub Sink Connector Testing:</h3><ul><li>Monitor the Pub/Sub subscription for incoming messages</li><li>Check connector logs for any processing issues</li><li>Verify message format and conversion</li></ul><h3>For Pub/Sub Source Connector Testing:</h3><ul><li>Review connector logs for successful message processing</li><li>Monitor the script output for consumed messages</li><li>Validate data integrity through the pipeline</li></ul><h3>Common Gotchas and Tips</h3><p>During my testing, I encountered a few challenges you might face:</p><p><strong>Message Format Issues</strong>: Pay attention to message serialization formats. ByteArrayConverter expects binary data, while StringConverter works with text messages.</p><p><strong>Network Connectivity</strong>: Ensure your firewall rules allow traffic between all components. The Private Service Connect setup can be tricky if not configured properly.</p><p><strong>Authentication</strong>: Double-check that all service accounts have the necessary permissions and that credentials are properly configured.</p><h3>Wrapping Up</h3><p>This integration between Managed Kafka and Pub/Sub opens up powerful possibilities for building scalable data pipelines on Google Cloud. The ability to seamlessly move data between these services enables hybrid architectures that leverage the best of both worlds.</p><p>The setup might seem complex initially, but once configured, it provides a robust foundation for real-time data processing workflows. Whether you’re building event-driven micro-services or complex data transformation pipelines, this connector pattern is incredibly valuable.</p><p>Have you worked with similar integrations? I’d love to hear about your experiences and any challenges you’ve encountered. Drop a comment below and let’s discuss!</p><p><em>All the code and configuration files mentioned in this post are available in </em><a href="https://github.com/atul-sutar/gcp-kafka-basic"><em>my GitHub repository</em></a><em>. Feel free to clone and experiment with the setup!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bff7831836de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Some Handy BigQuery Features]]></title>
            <link>https://atul-sutar.medium.com/exploring-advanced-features-in-bigquery-a5b40e53c6a9?source=rss-9079fe4063cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5b40e53c6a9</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Atul Sutar]]></dc:creator>
            <pubDate>Fri, 30 May 2025 11:17:08 GMT</pubDate>
            <atom:updated>2026-09-15T07:07:50.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjqLH87NQwL6XsePCy_r8Q.png" /></figure><p>Welcome to another post on <strong>Google BigQuery</strong>. In this article, we’ll take a closer look at some of the <strong>powerful and advanced features</strong> that every data engineer, analyst, or cloud architect should be familiar with when working in BigQuery.</p><p>This will be a <strong>concise and engaging overview</strong>, focusing on practical insights and capabilities that can significantly enhance your productivity and understanding of the platform.</p><h3>What We’ll Cover:</h3><ul><li>🔁 <strong>Time Travel in BigQuery</strong> — Accessing historical versions of your data</li><li>📊 <strong>Querying the INFORMATION_SCHEMA</strong> — Introspecting metadata and managing resources efficiently</li><li>🛠️ <strong>Handy Built-in Functions</strong> — A few must-know SQL functions for advanced queries</li><li>⚙️ <strong>Getting Started with Stored Procedures</strong> — Automating multi-step logic within BigQuery</li></ul><p>Let’s dive in and explore how these features can take your BigQuery skills to the next level!</p><h3><strong>Time Travel in BigQuery</strong></h3><p>The default time zone for timestamp_expression in a FOR SYSTEM_TIME AS OF expression is America/Los_Angeles, even though the default time zone for timestamp literals is UTC.</p><pre>SELECT *<br>FROM t<br>  FOR SYSTEM_TIME AS OF TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR);</pre><pre>SELECT *<br>FROM t<br>  FOR SYSTEM_TIME AS OF &#39;2017-01-01 10:00:00-07:00&#39;;</pre><p>The following operations show accessing a historical version of the table before table is replaced.</p><pre>DECLARE before_replace_timestamp TIMESTAMP;<br><br>-- Create table books.<br>CREATE TABLE books AS<br>SELECT &#39;Hamlet&#39; title, &#39;William Shakespeare&#39; author;<br><br>-- Get current timestamp before table replacement.<br>SET before_replace_timestamp = CURRENT_TIMESTAMP();<br><br>-- Replace table with different schema(title and release_date).<br>CREATE OR REPLACE TABLE books AS<br>SELECT &#39;Hamlet&#39; title, DATE &#39;1603-01-01&#39; release_date;<br><br>-- This query returns Hamlet, William Shakespeare as result.<br>SELECT * FROM books FOR SYSTEM_TIME AS OF before_replace_timestamp;</pre><pre>DECLARE JOB_START_TIMESTAMP TIMESTAMP;<br><br>-- Create table books.<br>CREATE OR REPLACE TABLE books AS<br>SELECT &#39;Hamlet&#39; title, &#39;William Shakespeare&#39; author;<br><br>-- Insert two rows into the books.<br>INSERT books (title, author)<br>VALUES(&#39;The Great Gatsby&#39;, &#39;F. Scott Fizgerald&#39;),<br>      (&#39;War and Peace&#39;, &#39;Leo Tolstoy&#39;);<br><br>SELECT * FROM books;<br><br>SET JOB_START_TIMESTAMP = (<br>  SELECT start_time<br>  FROM `region-us`.INFORMATION_SCHEMA.JOBS_BY_USER<br>  WHERE job_type=&quot;QUERY&quot;<br>    AND statement_type=&quot;INSERT&quot;<br>  ORDER BY start_time DESC<br>  LIMIT 1<br> );<br><br>-- This query only returns Hamlet, William Shakespeare as result.<br>SELECT * FROM books FOR SYSTEM_TIME AS OF JOB_START_TIMESTAMP;</pre><pre>INSERT INTO t1<br>SELECT * FROM t1<br>  FOR SYSTEM_TIME AS OF TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 DAY);</pre><h3><strong>Querying the INFORMATION_SCHEMA</strong></h3><p>The BigQuery INFORMATION_SCHEMA views are read-only, system-defined views that provide metadata information about your BigQuery objects.</p><pre>-- Returns metadata for tables in a single dataset.<br>SELECT * FROM myDataset.INFORMATION_SCHEMA.TABLES;</pre><pre>-- Returns metadata for all datasets in a region.<br>SELECT * FROM region-us.INFORMATION_SCHEMA.SCHEMATA;</pre><pre>-- Returns metadata for the specified project and region.<br>SELECT * FROM myProject.`region-us`.INFORMATION_SCHEMA.TABLES;<br><br>-- Returns metadata for the specified project and dataset.<br>SELECT * FROM myProject.myDataset.INFORMATION_SCHEMA.TABLES;</pre><h3><strong>Handy Built-in Functions</strong></h3><p>will see some useful ranking functions</p><h4>RANK</h4><p>Gives a rank to each row based on order. Tied values get the same rank, and the next rank is skipped.</p><pre>SELECT<br>  name,<br>  score,<br>  RANK() OVER (ORDER BY score DESC) AS rank<br>FROM (<br>  SELECT &#39;Alice&#39; AS name, 95 UNION ALL<br>  SELECT &#39;Bob&#39;, 88 UNION ALL<br>  SELECT &#39;Charlie&#39;, 95 UNION ALL<br>  SELECT &#39;David&#39;, 82 UNION ALL<br>  SELECT &#39;Eve&#39;, 88<br>);<br><br>+---------+-------+------+<br>| name    | score | rank |<br>+---------+-------+------+<br>| Alice   | 95    | 1    |<br>| Charlie | 95    | 1    |<br>| Bob     | 88    | 3    |<br>| Eve     | 88    | 3    |<br>| David   | 82    | 5    |<br>+---------+-------+------+</pre><h4>DENSE_RANK</h4><p>Similar to RANK(), but doesn&#39;t skip numbers after ties.</p><pre>SELECT<br>  name,<br>  score,<br>  DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank<br>FROM (<br>  SELECT &#39;Alice&#39; AS name, 95 UNION ALL<br>  SELECT &#39;Bob&#39;, 88 UNION ALL<br>  SELECT &#39;Charlie&#39;, 95 UNION ALL<br>  SELECT &#39;David&#39;, 82 UNION ALL<br>  SELECT &#39;Eve&#39;, 88<br>);<br><br>+---------+-------+------------+<br>| name    | score | dense_rank |<br>+---------+-------+------------+<br>| Alice   | 95    | 1          |<br>| Charlie | 95    | 1          |<br>| Bob     | 88    | 2          |<br>| Eve     | 88    | 2          |<br>| David   | 82    | 3          |<br>+---------+-------+------------+</pre><h4>ROW_NUMBER</h4><p>Gives a unique number to each row, regardless of duplicate values.</p><pre>SELECT<br>  name,<br>  score,<br>  ROW_NUMBER() OVER (ORDER BY score DESC) AS row_number<br>FROM (<br>  SELECT &#39;Alice&#39; AS name, 95 UNION ALL<br>  SELECT &#39;Bob&#39;, 88 UNION ALL<br>  SELECT &#39;Charlie&#39;, 95 UNION ALL<br>  SELECT &#39;David&#39;, 82 UNION ALL<br>  SELECT &#39;Eve&#39;, 88<br>);<br><br>+---------+-------+------------+<br>| name    | score | row_number |<br>+---------+-------+------------+<br>| Alice   | 95    | 1          |<br>| Charlie | 95    | 2          |<br>| Bob     | 88    | 3          |<br>| Eve     | 88    | 4          |<br>| David   | 82    | 5          |<br>+---------+-------+------------+</pre><h4>NTILE</h4><p>Splits the result into <strong>n equal groups (tiles)</strong> and numbers them.</p><pre>SELECT<br>  name,<br>  score,<br>  NTILE(3) OVER (ORDER BY score DESC) AS tile<br>FROM (<br>  SELECT &#39;Alice&#39; AS name, 95 UNION ALL<br>  SELECT &#39;Bob&#39;, 88 UNION ALL<br>  SELECT &#39;Charlie&#39;, 95 UNION ALL<br>  SELECT &#39;David&#39;, 82 UNION ALL<br>  SELECT &#39;Eve&#39;, 88 UNION ALL<br>  SELECT &#39;Frank&#39;, 80<br>);<br><br>+--------+-------+-------+<br>| name   | score | tile  |<br>+--------+-------+-------+<br>| Alice  | 95    | 1     |<br>| Charlie| 95    | 1     |<br>| Bob    | 88    | 2     |<br>| Eve    | 88    | 2     |<br>| David  | 82    | 3     |<br>| Frank  | 80    | 3     |<br>+--------+-------+-------+</pre><h3><strong>Getting Started with Stored Procedures</strong></h3><p>creating a stored procedure</p><p>To create a procedure, use the <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_procedure">CREATE PROCEDURE</a> statement.</p><p>In the following conceptual example, procedure_name represents the procedure and the body of the procedure appears between <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#begin">BEGIN</a> and END statements:</p><pre>CREATE PROCEDURE dataset_name.procedure_name()<br>BEGIN<br>-- statements here<br>END</pre><pre>CREATE OR REPLACE PROCEDURE mydataset.create_customer()<br>BEGIN<br>  DECLARE id STRING;<br>  SET id = GENERATE_UUID();<br>  INSERT INTO mydataset.customers (customer_id)<br>    VALUES(id);<br>  SELECT FORMAT(&quot;Created customer %s&quot;, id);<br>END</pre><p>calling a stored procedure</p><pre>CALL mydataset.create_customer();</pre><p>Stored Procedures with input parameters</p><pre>CREATE OR REPLACE PROCEDURE mydataset.create_customer(name STRING)<br>BEGIN<br>DECLARE id STRING;<br>SET id = GENERATE_UUID();<br>INSERT INTO mydataset.customers (customer_id, name)<br>  VALUES(id, name);<br>SELECT FORMAT(&quot;Created customer %s (%s)&quot;, id, name);<br>END</pre><p>Pass value out with output parameter</p><pre>CREATE OR REPLACE PROCEDURE mydataset.create_customer(name STRING, OUT id STRING)<br>BEGIN<br>SET id = GENERATE_UUID();<br>INSERT INTO mydataset.customers (customer_id, name)<br>  VALUES(id, name);<br>SELECT FORMAT(&quot;Created customer %s (%s)&quot;, id, name);<br>END</pre><pre>--- Create a new customer record.<br>DECLARE id STRING;<br>SET id = CALL mydataset.create_customer(&quot;alice&quot;,id);<br><br>--- Display the record.<br>SELECT * FROM mydataset.customers<br>WHERE customer_id = id;</pre><p>Call built in system procedures</p><pre>CALL BQ.REFRESH_MATERIALIZED_VIEW;</pre><p>References</p><ul><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#from_clause">Query syntax | BigQuery | Google Cloud</a></li><li><a href="https://cloud.google.com/bigquery/docs/information-schema-intro">Introduction to INFORMATION_SCHEMA | BigQuery | Google Cloud</a></li><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/numbering_functions#rank">Numbering functions | BigQuery | Google Cloud</a></li><li><a href="https://cloud.google.com/bigquery/docs/procedures">Work with SQL stored procedures | BigQuery | Google Cloud</a></li></ul><p>I’ll continue to add deeper insights into BigQuery in upcoming posts. Thanks for following along — more to come!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5b40e53c6a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reflections on Becoming a Google Cloud Professional Cloud Architect]]></title>
            <link>https://atul-sutar.medium.com/reflections-on-becoming-a-google-cloud-professional-cloud-architect-8b88caa0270f?source=rss-9079fe4063cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b88caa0270f</guid>
            <category><![CDATA[gcp-architecture]]></category>
            <category><![CDATA[gcp-architect]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cloud-services]]></category>
            <dc:creator><![CDATA[Atul Sutar]]></dc:creator>
            <pubDate>Fri, 30 May 2025 10:42:03 GMT</pubDate>
            <atom:updated>2026-09-15T07:07:01.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z812nCk9M7buaW2oi965YQ.png" /></figure><p>I’m excited to share that I recently earned the <strong>Google Cloud Professional Cloud Architect certification</strong>. This was my first time taking this particular certification exam, and I’d like to take a moment to reflect on the journey — what it involved, how I prepared, and what I learned along the way.</p><h3>The Starting Point</h3><p>When I first decided to pursue this certification, I had very little idea where to begin or how to structure my preparation. The scope of the exam was broad, covering a wide array of <strong>Google Cloud Platform (GCP)</strong> services, architectural best practices, and real-world scenarios. It was clear from the start that this wasn’t just about memorizing services — it was about <strong>understanding how to architect end-to-end solutions</strong> in GCP.</p><p>I dedicated around <strong>six weeks</strong> to focused preparation. During this time, I leveraged various learning resources including:</p><ul><li><strong>Official Google Cloud documentation: </strong><a href="https://cloud.google.com/learn/certification/cloud-architect"><strong>Certification</strong></a><strong>, </strong><a href="https://cloud.google.com/learn/certification/guides/professional-cloud-architect"><strong>Exam Guide</strong></a><strong>, </strong><a href="https://cloud.google.com/products?hl=en"><strong>Products and Services</strong></a></li><li><strong>Online courses: </strong><a href="https://www.cloudskillsboost.google/paths/12"><strong>Google Qwiklabs</strong></a><strong>, </strong><a href="https://www.udemy.com/course/google-cloud-professional-cloud-architect-certification/?couponCode=LEARNNOWPLANS"><strong>Udemy Course</strong></a></li><li><strong>Practice exams: Google Practice questions and tests from Udemy should suffice</strong></li></ul><h3>Thinking Like an Architect</h3><p>One of the most valuable aspects of the preparation process was learning to think like a cloud architect. The exam isn’t just about knowing what each GCP service does — it’s about <strong>evaluating trade-offs, selecting the optimal solution for specific business requirements, and designing scalable, secure, and cost-effective architectures</strong>.</p><p>Throughout my study, I encountered case studies based on fictional companies (Google provides four in total — two of which appear on the exam). These were incredibly useful in simulating real-world scenarios, where you must:</p><ul><li>Understand business and technical requirements</li><li>Design appropriate cloud-based solutions using GCP products</li><li>Justify choices based on performance, cost, reliability, and security</li></ul><p>This approach helped me internalize the mindset of a cloud architect: someone who not only understands technology, but also how to align it with <strong>strategic goals and operational constraints</strong>.</p><h3>Key Learnings</h3><p>Here are a few technical and strategic takeaways from my journey:</p><ul><li>Understanding the <strong>interplay between compute, storage, and networking services</strong> is crucial (e.g., choosing between GKE, App Engine, and Cloud Run based on scalability and control requirements).</li><li>Security and IAM policies should be <strong>designed from the ground up</strong>, not as an afterthought.</li><li>Knowing <strong>hybrid and multi-cloud patterns</strong>, such as using Anthos, can set you apart.</li><li>Performance tuning and cost optimization are essential architectural skills — not just bonus knowledge.</li></ul><h3>Final Thoughts</h3><p>This experience was not only rewarding but also transformative. I discovered how much I enjoy the process of <strong>problem-solving, researching services, designing robust pipelines, and building resilient cloud architectures</strong>. This certification validated that I’m on the right path professionally. also don’t forgot to check googles <a href="https://cloud.google.com/architecture">architecture guidelines and topologies</a>.</p><p>If you’re considering this certification or have any questions about preparation strategies or resources, feel free to reach out — I’d be happy to help.</p><p><a href="https://www.credly.com/badges/1ecb97c8-01c9-4343-9a5b-a2e6f7d44859/public_url">Credential</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EsvnwntKyYAWfACaX4yBmQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b88caa0270f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BigQuery SQL Syntax Guide]]></title>
            <link>https://atul-sutar.medium.com/bigquery-sql-syntax-guide-87ad9cfb74ce?source=rss-9079fe4063cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/87ad9cfb74ce</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[sql-syntax]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Atul Sutar]]></dc:creator>
            <pubDate>Fri, 30 May 2025 07:41:19 GMT</pubDate>
            <atom:updated>2026-09-15T07:06:05.517Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sFLmZz18kMpWtciOy0-Fg.png" /></figure><p><strong>Welcome!</strong><br> In today’s post, we’ll explore some of the most commonly used BigQuery SQL syntax. I’ve curated this guide to be concise, easy to understand, and quick to read — perfect for anyone working with BigQuery on a day-to-day basis.</p><p>Let’s dive in!</p><h3><strong>Select Statements</strong></h3><h4><strong>SELECT</strong></h4><p>The SELECT list defines the columns that the query will return. Expressions in the SELECT list can refer to columns in any of the from_items in its corresponding FROM clause.</p><pre><br>SELECT fruit FROM (SELECT &quot;apple&quot; AS fruit, &quot;carrot&quot; AS vegetable);<br>SELECT * FROM (SELECT &quot;apple&quot; AS fruit, &quot;carrot&quot; AS vegetable);<br><br>/*-------+-----------*<br> | fruit | vegetable |<br> +-------+-----------+<br> | apple | carrot    |<br> *-------+-----------*/<br></pre><h4><strong>SELECT EXCEPT</strong></h4><p>A SELECT * EXCEPT statement specifies the names of one or more columns to exclude from the result. All matching column names are omitted from the output.</p><pre>WITH orders AS<br>  (SELECT 5 as order_id,<br>  &quot;sprocket&quot; as item_name,<br>  200 as quantity)<br>SELECT * EXCEPT (order_id)<br>FROM orders;<br><br>/*-----------+----------*<br> | item_name | quantity |<br> +-----------+----------+<br> | sprocket  | 200      |<br> *-----------+----------*/</pre><h4><strong>SELECT REPLACE</strong></h4><p>A SELECT * REPLACE statement specifies one or more expression AS identifier clauses. Each identifier must match a column name from the SELECT * statement. In the output column list, the column that matches the identifier in a REPLACE clause is replaced by the expression in that REPLACE clause.</p><pre>WITH orders AS<br>  (SELECT 5 as order_id,<br>  &quot;sprocket&quot; as item_name,<br>  200 as quantity)<br>SELECT * REPLACE (quantity/2 AS quantity)<br>FROM orders;<br><br>/*----------+-----------+----------*<br> | order_id | item_name | quantity |<br> +----------+-----------+----------+<br> | 5        | sprocket  | 100      |<br> *----------+-----------+----------*/</pre><h4><strong>SELECT DISTINCT</strong></h4><p>A SELECT DISTINCT statement discards duplicate rows and returns only the remaining rows.</p><pre>WITH PlayerStats AS (<br>  SELECT [&#39;Coolidge&#39;, &#39;Adams&#39;] as Name, 3 as PointsScored UNION ALL<br>  SELECT [&#39;Adams&#39;, &#39;Buchanan&#39;], 0 UNION ALL<br>  SELECT [&#39;Coolidge&#39;, &#39;Adams&#39;], 1 UNION ALL<br>  SELECT [&#39;Kiran&#39;, &#39;Noam&#39;], 1)<br>SELECT DISTINCT Name<br>FROM PlayerStats;<br><br>/*------------------+<br> | Name             |<br> +------------------+<br> | [Coolidge,Adams] |<br> | [Adams,Buchanan] |<br> | [Kiran,Noam]     |<br> +------------------*/</pre><h4><strong>SELECT ALL</strong></h4><p>A SELECT ALL statement returns all rows, including duplicate rows. SELECT ALL is the default behavior of SELECT.</p><h4>SELECT AS STRUCT</h4><p>This produces a <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#value_tables">value table</a> with a STRUCT row type, where the STRUCT field names and types match the column names and types produced in the SELECT list.</p><pre>SELECT ARRAY(SELECT AS STRUCT 1 a, 2 b)</pre><h3>FROM Clause</h3><p>The FROM clause indicates the table or tables from which to retrieve rows, and specifies how to join those rows together to produce a single stream of rows for processing in the rest of the query.</p><pre>SELECT * FROM Roster;<br>SELECT * FROM dataset.Roster;<br>SELECT * FROM project.dataset.Roster;</pre><p>In the FROM clause, field_path is any path that resolves to a field within a data type. field_path can go arbitrarily deep into a nested data structure.</p><pre>SELECT * FROM T1 t1, t1.array_column;<br><br>SELECT * FROM T1 t1, t1.struct_column.array_field;<br><br>SELECT (SELECT ARRAY_AGG(c) FROM t1.array_column c) FROM T1 t1;<br><br>SELECT a.struct_field1 FROM T1 t1, t1.array_of_structs a;<br><br>SELECT (SELECT STRING_AGG(a.struct_field1) FROM t1.array_of_structs a) FROM T1 t1;</pre><h3>UNNEST Operator</h3><p>The UNNEST operator takes an array and returns a table with one row for each element in the array. The output of UNNEST is one <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#value_tables">value table</a> column. For these ARRAY element types, SELECT * against the value table column returns multiple columns:</p><pre>SELECT * FROM UNNEST ([10,20,30]) as numbers WITH OFFSET;<br><br>/*---------+--------*<br> | numbers | offset |<br> +---------+--------+<br> | 10      | 0      |<br> | 20      | 1      |<br> | 30      | 2      |<br> *---------+--------*/</pre><h4>UNNEST and Struct</h4><p>For an input array of structs, UNNEST returns a row for each struct, with a separate column for each field in the struct. The alias for each column is the name of the corresponding struct field.</p><pre>SELECT *<br>FROM UNNEST(<br>  ARRAY&lt;<br>    STRUCT&lt;<br>      x INT64,<br>      y STRING,<br>      z STRUCT&lt;a INT64, b INT64&gt;&gt;&gt;[<br>        (1, &#39;foo&#39;, (10, 11)),<br>        (3, &#39;bar&#39;, (20, 21))]);<br><br>/*---+-----+----------*<br> | x | y   | z        |<br> +---+-----+----------+<br> | 1 | foo | {10, 11} |<br> | 3 | bar | {20, 21} |<br> *---+-----+----------*/</pre><h4>Explicit UNNEST</h4><pre>WITH Coordinates AS (SELECT [1,2] AS position)<br>SELECT results FROM Coordinates, UNNEST(Coordinates.position) AS results;</pre><h4>Implicit UNNEST</h4><pre>WITH Coordinates AS (SELECT [1,2] AS position)<br>SELECT results FROM Coordinates, Coordinates.position AS results;</pre><h4>UNNEST and NULL Values</h4><p>UNNEST treats NULL values as follows:</p><ul><li>NULL and empty arrays produce zero rows.</li><li>An array containing NULL values produces rows containing NULL values.</li></ul><h3>PIVOT Operator</h3><p>The PIVOT operator rotates rows into columns, using aggregation. PIVOT is part of the FROM clause.</p><pre>WITH Produce AS (<br>  SELECT &#39;Kale&#39; as product, 51 as sales, &#39;Q1&#39; as quarter, 2020 as year UNION ALL<br>  SELECT &#39;Kale&#39;, 23, &#39;Q2&#39;, 2020 UNION ALL<br>  SELECT &#39;Kale&#39;, 45, &#39;Q3&#39;, 2020 UNION ALL<br>  SELECT &#39;Kale&#39;, 3, &#39;Q4&#39;, 2020 UNION ALL<br>  SELECT &#39;Kale&#39;, 70, &#39;Q1&#39;, 2021 UNION ALL<br>  SELECT &#39;Kale&#39;, 85, &#39;Q2&#39;, 2021 UNION ALL<br>  SELECT &#39;Apple&#39;, 77, &#39;Q1&#39;, 2020 UNION ALL<br>  SELECT &#39;Apple&#39;, 0, &#39;Q2&#39;, 2020 UNION ALL<br>  SELECT &#39;Apple&#39;, 1, &#39;Q1&#39;, 2021)<br>SELECT * FROM Produce<br><br>/*---------+-------+---------+------*<br> | product | sales | quarter | year |<br> +---------+-------+---------+------|<br> | Kale    | 51    | Q1      | 2020 |<br> | Kale    | 23    | Q2      | 2020 |<br> | Kale    | 45    | Q3      | 2020 |<br> | Kale    | 3     | Q4      | 2020 |<br> | Kale    | 70    | Q1      | 2021 |<br> | Kale    | 85    | Q2      | 2021 |<br> | Apple   | 77    | Q1      | 2020 |<br> | Apple   | 0     | Q2      | 2020 |<br> | Apple   | 1     | Q1      | 2021 |<br> *---------+-------+---------+------*/<br><br><br>SELECT * FROM<br>  Produce<br>  PIVOT(SUM(sales) FOR quarter IN (&#39;Q1&#39;, &#39;Q2&#39;, &#39;Q3&#39;, &#39;Q4&#39;))<br><br>/*---------+------+----+------+------+------*<br> | product | year | Q1 | Q2   | Q3   | Q4   |<br> +---------+------+----+------+------+------+<br> | Apple   | 2020 | 77 | 0    | NULL | NULL |<br> | Apple   | 2021 | 1  | NULL | NULL | NULL |<br> | Kale    | 2020 | 51 | 23   | 45   | 3    |<br> | Kale    | 2021 | 70 | 85   | NULL | NULL |<br> *---------+------+----+------+------+------*/<br><br>-- If you don&#39;t include year, then SUM is grouped only by product.<br><br>SELECT * FROM<br>  (SELECT product, sales, quarter FROM Produce)<br>  PIVOT(SUM(sales) FOR quarter IN (&#39;Q1&#39;, &#39;Q2&#39;, &#39;Q3&#39;, &#39;Q4&#39;))<br><br>/*---------+-----+-----+------+------*<br> | product | Q1  | Q2  | Q3   | Q4   |<br> +---------+-----+-----+------+------+<br> | Apple   | 78  | 0   | NULL | NULL |<br> | Kale    | 121 | 108 | 45   | 3    |<br> *---------+-----+-----+------+------*/</pre><p>You can include multiple aggregation functions in the PIVOT. In this case, you must specify an alias for each aggregation. These aliases are used to construct the column names in the resulting table.</p><pre>SELECT * FROM<br>  (SELECT product, sales, quarter FROM Produce)<br>  PIVOT(SUM(sales) AS total_sales, COUNT(*) AS num_records FOR quarter IN (&#39;Q1&#39;, &#39;Q2&#39;))<br><br>/*--------+----------------+----------------+----------------+----------------*<br> |product | total_sales_Q1 | num_records_Q1 | total_sales_Q2 | num_records_Q2 |<br> +--------+----------------+----------------+----------------+----------------+<br> | Kale   | 121            | 2              | 108            | 2              |<br> | Apple  | 78             | 2              | 0              | 1              |<br> *--------+----------------+----------------+----------------+----------------*/</pre><h3>UNPIVOT Operator</h3><p>The UNPIVOT operator rotates columns into rows. UNPIVOT is part of the FROM clause.</p><pre>WITH Produce AS (<br>  SELECT &#39;Kale&#39; as product, 51 as Q1, 23 as Q2, 45 as Q3, 3 as Q4 UNION ALL<br>  SELECT &#39;Apple&#39;, 77, 0, 25, 2)<br>SELECT * FROM Produce<br><br>/*---------+----+----+----+----*<br> | product | Q1 | Q2 | Q3 | Q4 |<br> +---------+----+----+----+----+<br> | Kale    | 51 | 23 | 45 | 3  |<br> | Apple   | 77 | 0  | 25 | 2  |<br> *---------+----+----+----+----*/<br><br><br>SELECT * FROM Produce<br>UNPIVOT(sales FOR quarter IN (Q1, Q2, Q3, Q4))<br><br>/*---------+-------+---------*<br> | product | sales | quarter |<br> +---------+-------+---------+<br> | Kale    | 51    | Q1      |<br> | Kale    | 23    | Q2      |<br> | Kale    | 45    | Q3      |<br> | Kale    | 3     | Q4      |<br> | Apple   | 77    | Q1      |<br> | Apple   | 0     | Q2      |<br> | Apple   | 25    | Q3      |<br> | Apple   | 2     | Q4      |<br> *---------+-------+---------*/</pre><p>In this example, we UNPIVOT four quarters into two semesters. This is a multi-column unpivot operation.</p><pre>SELECT * FROM Produce<br>UNPIVOT(<br>  (first_half_sales, second_half_sales)<br>  FOR semesters<br>  IN ((Q1, Q2) AS &#39;semester_1&#39;, (Q3, Q4) AS &#39;semester_2&#39;))<br><br>/*---------+------------------+-------------------+------------*<br> | product | first_half_sales | second_half_sales | semesters  |<br> +---------+------------------+-------------------+------------+<br> | Kale    | 51               | 23                | semester_1 |<br> | Kale    | 45               | 3                 | semester_2 |<br> | Apple   | 77               | 0                 | semester_1 |<br> | Apple   | 25               | 2                 | semester_2 |<br> *---------+------------------+-------------------+------------*/</pre><h3>TABLESAMPLE operator</h3><p>You can use the TABLESAMPLE operator to select a random sample of a dataset. This operator is useful when you&#39;re working with tables that have large amounts of data and you don&#39;t need precise answers.</p><pre>SELECT * FROM dataset.my_table TABLESAMPLE SYSTEM (10 PERCENT)</pre><h3>JOIN Operation</h3><h4>[Inner] JOIN</h4><p>An INNER JOIN, or simply JOIN, effectively calculates the Cartesian product of the two from_items and discards all rows that don&#39;t meet the join condition.</p><pre>FROM A INNER JOIN B ON A.w = B.y<br><br>/*<br>Table A       Table B       Result<br>+-------+     +-------+     +---------------+<br>| w | x |  *  | y | z |  =  | w | x | y | z |<br>+-------+     +-------+     +---------------+<br>| 1 | a |     | 2 | k |     | 2 | b | 2 | k |<br>| 2 | b |     | 3 | m |     | 3 | c | 3 | m |<br>| 3 | c |     | 3 | n |     | 3 | c | 3 | n |<br>| 3 | d |     | 4 | p |     | 3 | d | 3 | m |<br>+-------+     +-------+     | 3 | d | 3 | n |<br>                            +---------------+<br>*/<br><br>SELECT Roster.LastName, TeamMascot.Mascot<br>FROM Roster JOIN TeamMascot ON Roster.SchoolID = TeamMascot.SchoolID;<br><br>/*---------------------------*<br> | LastName   | Mascot       |<br> +---------------------------+<br> | Adams      | Jaguars      |<br> | Buchanan   | Lakers       |<br> | Coolidge   | Lakers       |<br> | Davis      | Knights      |<br> *---------------------------*/</pre><h4>CROSS JOIN</h4><p>CROSS JOIN returns the Cartesian product of the two from_items. In other words, it combines each row from the first from_item with each row from the second from_item.</p><pre>FROM A CROSS JOIN B<br><br>/*<br>Table A       Table B       Result<br>+-------+     +-------+     +---------------+<br>| w | x |  *  | y | z |  =  | w | x | y | z |<br>+-------+     +-------+     +---------------+<br>| 1 | a |     | 2 | c |     | 1 | a | 2 | c |<br>| 2 | b |     | 3 | d |     | 1 | a | 3 | d |<br>+-------+     +-------+     | 2 | b | 2 | c |<br>                            | 2 | b | 3 | d |<br>                            +---------------+<br>*/<br><br>SELECT Roster.LastName, TeamMascot.Mascot<br>FROM Roster CROSS JOIN TeamMascot;<br><br>/*---------------------------*<br> | LastName   | Mascot       |<br> +---------------------------+<br> | Adams      | Jaguars      |<br> | Adams      | Knights      |<br> | Adams      | Lakers       |<br> | Adams      | Mustangs     |<br> | Buchanan   | Jaguars      |<br> | Buchanan   | Knights      |<br> | Buchanan   | Lakers       |<br> | Buchanan   | Mustangs     |<br> | ...                       |<br> *---------------------------*/</pre><h4>Comma cross JOIN (,)</h4><p><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#cross_join">CROSS JOIN</a> can be written implicitly with a comma.</p><pre>FROM A, B<br><br>/*<br>Table A       Table B       Result<br>+-------+     +-------+     +---------------+<br>| w | x |  *  | y | z |  =  | w | x | y | z |<br>+-------+     +-------+     +---------------+<br>| 1 | a |     | 2 | c |     | 1 | a | 2 | c |<br>| 2 | b |     | 3 | d |     | 1 | a | 3 | d |<br>+-------+     +-------+     | 2 | b | 2 | c |<br>                            | 2 | b | 3 | d |<br>                            +---------------+<br>*/<br><br>SELECT Roster.LastName, TeamMascot.Mascot<br>FROM Roster, TeamMascot;<br><br>/*---------------------------*<br> | LastName   | Mascot       |<br> +---------------------------+<br> | Adams      | Jaguars      |<br> | Adams      | Knights      |<br> | Adams      | Lakers       |<br> | Adams      | Mustangs     |<br> | Buchanan   | Jaguars      |<br> | Buchanan   | Knights      |<br> | Buchanan   | Lakers       |<br> | Buchanan   | Mustangs     |<br> | ...                       |<br> *---------------------------*/</pre><h4>FULL [OUTER] JOIN</h4><p>A FULL OUTER JOIN (or simply FULL JOIN) returns all fields for all matching rows in both from_items that meet the join condition. If a given row from one from_item doesn&#39;t join to any row in the other from_item, the row returns with NULL values for all columns from the other from_item.</p><pre>FROM A FULL OUTER JOIN B ON A.w = B.y<br><br>/*<br>Table A       Table B       Result<br>+-------+     +-------+     +---------------------------+<br>| w | x |  *  | y | z |  =  | w    | x    | y    | z    |<br>+-------+     +-------+     +---------------------------+<br>| 1 | a |     | 2 | k |     | 1    | a    | NULL | NULL |<br>| 2 | b |     | 3 | m |     | 2    | b    | 2    | k    |<br>| 3 | c |     | 3 | n |     | 3    | c    | 3    | m    |<br>| 3 | d |     | 4 | p |     | 3    | c    | 3    | n    |<br>+-------+     +-------+     | 3    | d    | 3    | m    |<br>                            | 3    | d    | 3    | n    |<br>                            | NULL | NULL | 4    | p    |<br>                            +---------------------------+<br>*/<br><br><br>SELECT Roster.LastName, TeamMascot.Mascot<br>FROM Roster FULL JOIN TeamMascot ON Roster.SchoolID = TeamMascot.SchoolID;<br><br>/*---------------------------*<br> | LastName   | Mascot       |<br> +---------------------------+<br> | Adams      | Jaguars      |<br> | Buchanan   | Lakers       |<br> | Coolidge   | Lakers       |<br> | Davis      | Knights      |<br> | Eisenhower | NULL         |<br> | NULL       | Mustangs     |<br> *---------------------------*/</pre><h4>LEFT [OUTER] JOIN</h4><p>The result of a LEFT OUTER JOIN (or simply LEFT JOIN) for two from_items always retains all rows of the left from_item in the JOIN operation, even if no rows in the right from_item satisfy the join predicate.</p><pre>FROM A LEFT OUTER JOIN B ON A.w = B.y<br><br>/*<br>Table A       Table B       Result<br>+-------+     +-------+     +---------------------------+<br>| w | x |  *  | y | z |  =  | w    | x    | y    | z    |<br>+-------+     +-------+     +---------------------------+<br>| 1 | a |     | 2 | k |     | 1    | a    | NULL | NULL |<br>| 2 | b |     | 3 | m |     | 2    | b    | 2    | k    |<br>| 3 | c |     | 3 | n |     | 3    | c    | 3    | m    |<br>| 3 | d |     | 4 | p |     | 3    | c    | 3    | n    |<br>+-------+     +-------+     | 3    | d    | 3    | m    |<br>                            | 3    | d    | 3    | n    |<br>                            +---------------------------+<br>*/<br><br>SELECT Roster.LastName, TeamMascot.Mascot<br>FROM Roster LEFT JOIN TeamMascot ON Roster.SchoolID = TeamMascot.SchoolID;<br><br>/*---------------------------*<br> | LastName   | Mascot       |<br> +---------------------------+<br> | Adams      | Jaguars      |<br> | Buchanan   | Lakers       |<br> | Coolidge   | Lakers       |<br> | Davis      | Knights      |<br> | Eisenhower | NULL         |<br> *---------------------------*/</pre><h4>RIGHT [OUTER] JOIN</h4><p>The result of a RIGHT OUTER JOIN (or simply RIGHT JOIN) for two from_items always retains all rows of the right from_item in the JOIN operation, even if no rows in the left from_item satisfy the join predicate.</p><pre>FROM A RIGHT OUTER JOIN B ON A.w = B.y<br><br>/*<br>Table A       Table B       Result<br>+-------+     +-------+     +---------------------------+<br>| w | x |  *  | y | z |  =  | w    | x    | y    | z    |<br>+-------+     +-------+     +---------------------------+<br>| 1 | a |     | 2 | k |     | 2    | b    | 2    | k    |<br>| 2 | b |     | 3 | m |     | 3    | c    | 3    | m    |<br>| 3 | c |     | 3 | n |     | 3    | c    | 3    | n    |<br>| 3 | d |     | 4 | p |     | 3    | d    | 3    | m    |<br>+-------+     +-------+     | 3    | d    | 3    | n    |<br>                            | NULL | NULL | 4    | p    |<br>                            +---------------------------+<br>*/<br><br>SELECT Roster.LastName, TeamMascot.Mascot<br>FROM Roster RIGHT JOIN TeamMascot ON Roster.SchoolID = TeamMascot.SchoolID;<br><br>/*---------------------------*<br> | LastName   | Mascot       |<br> +---------------------------+<br> | Adams      | Jaguars      |<br> | Buchanan   | Lakers       |<br> | Coolidge   | Lakers       |<br> | Davis      | Knights      |<br> | NULL       | Mustangs     |<br> *---------------------------*/</pre><h4>JOIN operations in a sequence</h4><p>The FROM clause can contain multiple JOIN operations in a sequence. JOINs are bound from left to right. For example:</p><pre>FROM A JOIN B USING (x) JOIN C USING (x)<br><br>-- A JOIN B USING (x)        = result_1<br>-- result_1 JOIN C USING (x) = result_2<br>-- result_2                  = return value<br><br><br><br>-- parantheses to group JOIN&#39;s<br><br>FROM ( (A JOIN B USING (x)) JOIN C USING (x) )<br><br>-- A JOIN B USING (x)        = result_1<br>-- result_1 JOIN C USING (x) = result_2<br>-- result_2                  = return value<br><br><br>-- parantheses to group JOIN&#39;s in different order<br><br>FROM ( A JOIN (B JOIN C USING (x)) USING (x) )<br><br>-- B JOIN C USING (x)       = result_1<br>-- A JOIN result_1          = result_2<br>-- result_2                 = return value</pre><h3>WHERE Caluse</h3><p>The WHERE clause filters the results of the FROM clause.</p><p>Only rows whose bool_expression evaluates to TRUE are included. Rows whose bool_expression evaluates to NULL or FALSE are discarded.</p><p>The evaluation of a query with a WHERE clause is typically completed in this order:</p><ul><li>FROM</li><li>WHERE</li><li>GROUP BY and aggregation</li><li>HAVING</li><li>WINDOW</li><li>QUALIFY</li><li>DISTINCT</li><li>ORDER BY</li><li>LIMIT</li></ul><pre>SELECT * FROM Roster<br>WHERE SchoolID = 52;<br><br>SELECT * FROM Roster<br>WHERE STARTS_WITH(LastName, &quot;Mc&quot;) OR STARTS_WITH(LastName, &quot;Mac&quot;);</pre><h3>GROUP BY Clause</h3><p>The GROUP BY clause groups together rows in a table that share common values for certain columns. For a group of rows in the source table with non-distinct values, the GROUP BY clause aggregates them into a single combined row. This clause is commonly used when aggregate functions are present in the SELECT list, or to eliminate redundancy in the output.</p><pre>WITH PlayerStats AS (<br>  SELECT &#39;Adams&#39; as LastName, &#39;Noam&#39; as FirstName, 3 as PointsScored UNION ALL<br>  SELECT &#39;Buchanan&#39;, &#39;Jie&#39;, 0 UNION ALL<br>  SELECT &#39;Coolidge&#39;, &#39;Kiran&#39;, 1 UNION ALL<br>  SELECT &#39;Adams&#39;, &#39;Noam&#39;, 4 UNION ALL<br>  SELECT &#39;Buchanan&#39;, &#39;Jie&#39;, 13)<br>SELECT SUM(PointsScored) AS total_points, LastName<br>FROM PlayerStats<br>GROUP BY LastName;<br><br>/*--------------+----------+<br> | total_points | LastName |<br> +--------------+----------+<br> | 7            | Adams    |<br> | 13           | Buchanan |<br> | 1            | Coolidge |<br> +--------------+----------*/<br><br>WITH<br>  TeamStats AS (<br>    SELECT<br>      ARRAY&lt;STRUCT&lt;last_name STRING, first_name STRING, age INT64&gt;&gt;[<br>        (&#39;Adams&#39;, &#39;Noam&#39;, 20), (&#39;Buchanan&#39;, &#39;Jie&#39;, 19)] AS Team,<br>      3 AS PointsScored<br>    UNION ALL<br>    SELECT [(&#39;Coolidge&#39;, &#39;Kiran&#39;, 21), (&#39;Yang&#39;, &#39;Jason&#39;, 22)], 4<br>    UNION ALL<br>    SELECT [(&#39;Adams&#39;, &#39;Noam&#39;, 20), (&#39;Buchanan&#39;, &#39;Jie&#39;, 19)], 10<br>    UNION ALL<br>    SELECT [(&#39;Coolidge&#39;, &#39;Kiran&#39;, 21), (&#39;Yang&#39;, &#39;Jason&#39;, 22)], 7<br>  )<br>SELECT<br>  SUM(PointsScored) AS total_points,<br>  Team<br>FROM TeamStats<br>GROUP BY Team;<br><br>/*--------------+--------------------------+<br> | total_points | teams                    |<br> +--------------+--------------------------+<br> | 13           | [{                       |<br> |              |    last_name: &quot;Adams&quot;,   |<br> |              |    first_name: &quot;Noam&quot;,   |<br> |              |    age: 20               |<br> |              |  },{                     |<br> |              |    last_name: &quot;Buchanan&quot;,|<br> |              |    first_name: &quot;Jie&quot;,    |<br> |              |    age: 19               |<br> |              |  }]                      |<br> +-----------------------------------------+<br> | 11           | [{                       |<br> |              |    last_name: &quot;Coolidge&quot;,|<br> |              |    first_name: &quot;Kiran&quot;,  |<br> |              |    age: 21               |<br> |              |  },{                     |<br> |              |    last_name: &quot;Yang&quot;,    |<br> |              |    first_name: &quot;Jason&quot;,  |<br> |              |    age: 22               |<br> |              |  }]                      |<br> +--------------+--------------------------*/</pre><h4>GROUP BY ALL</h4><p>The GROUP BY ALL clause groups rows by inferring grouping keys from the SELECT items.</p><pre>WITH PlayerStats AS (<br>  SELECT &#39;Adams&#39; as LastName, &#39;Noam&#39; as FirstName, 3 as PointsScored UNION ALL<br>  SELECT &#39;Buchanan&#39;, &#39;Jie&#39;, 0 UNION ALL<br>  SELECT &#39;Coolidge&#39;, &#39;Kiran&#39;, 1 UNION ALL<br>  SELECT &#39;Adams&#39;, &#39;Noam&#39;, 4 UNION ALL<br>  SELECT &#39;Buchanan&#39;, &#39;Jie&#39;, 13)<br>SELECT<br>  SUM(PointsScored) AS total_points,<br>  FirstName AS first_name,<br>  LastName AS last_name<br>FROM PlayerStats<br>GROUP BY ALL;<br><br>/*--------------+------------+-----------+<br> | total_points | first_name | last_name |<br> +--------------+------------+-----------+<br> | 7            | Noam       | Adams     |<br> | 13           | Jie        | Buchanan  |<br> | 1            | Kiran      | Coolidge  |<br> +--------------+------------+-----------*/</pre><h3>HAVING Clause</h3><p>The HAVING clause filters the results produced by GROUP BY or aggregation. GROUP BY or aggregation must be present in the query. If aggregation is present, the HAVING clause is evaluated once for every aggregated row in the result set.</p><pre>SELECT LastName<br>FROM Roster<br>GROUP BY LastName<br>HAVING SUM(PointsScored) &gt; 15;<br><br>SELECT LastName, SUM(PointsScored) AS ps<br>FROM Roster<br>GROUP BY LastName<br>HAVING ps &gt; 0;</pre><h4>Mandatory aggregation</h4><p>Aggregation doesn’t have to be present in the HAVING clause itself, but aggregation must be present in at least one of the following forms:</p><pre>SELECT LastName, SUM(PointsScored) AS total<br>FROM PlayerStats<br>GROUP BY LastName<br>HAVING total &gt; 15;<br><br>SELECT LastName<br>FROM PlayerStats<br>GROUP BY LastName<br>HAVING SUM(PointsScored) &gt; 15;<br><br>SELECT LastName, COUNT(*)<br>FROM PlayerStats<br>GROUP BY LastName<br>HAVING SUM(PointsScored) &gt; 15;</pre><h3>ORDER BY Clause</h3><p>The ORDER BY clause specifies a column or expression as the sort criterion for the result set. If an ORDER BY clause isn&#39;t present, the order of the results of a query isn&#39;t defined.</p><p><strong>Optional Clauses</strong></p><ul><li>NULLS FIRST | NULLS LAST:</li><li>NULLS FIRST: Sort null values before non-null values.</li><li>NULLS LAST. Sort null values after non-null values.</li><li>ASC | DESC: Sort the results in ascending or descending order of expression values. ASC is the default value. If null ordering isn&#39;t specified with NULLS FIRST or NULLS LAST:</li><li>NULLS FIRST is applied by default if the sort order is ascending.</li><li>NULLS LAST is applied by default if the sort order is descending.</li></ul><pre>SELECT x, y<br>FROM (SELECT 1 AS x, true AS y UNION ALL<br>      SELECT 9, true UNION ALL<br>      SELECT NULL, false)<br>ORDER BY x;<br><br>/*------+-------*<br> | x    | y     |<br> +------+-------+<br> | NULL | false |<br> | 1    | true  |<br> | 9    | true  |<br> *------+-------*/<br><br><br>SELECT x, y<br>FROM (SELECT 1 AS x, true AS y UNION ALL<br>      SELECT 9, true UNION ALL<br>      SELECT NULL, false)<br>ORDER BY x NULLS LAST;<br><br>/*------+-------*<br> | x    | y     |<br> +------+-------+<br> | 1    | true  |<br> | 9    | true  |<br> | NULL | false |<br> *------+-------*/<br><br>SELECT x, y<br>FROM (SELECT 1 AS x, true AS y UNION ALL<br>      SELECT 9, true UNION ALL<br>      SELECT NULL, false)<br>ORDER BY x DESC;<br><br>/*------+-------*<br> | x    | y     |<br> +------+-------+<br> | 9    | true  |<br> | 1    | true  |<br> | NULL | false |<br> *------+-------*/<br><br>SELECT x, y<br>FROM (SELECT 1 AS x, true AS y UNION ALL<br>      SELECT 9, true UNION ALL<br>      SELECT NULL, false)<br>ORDER BY x DESC NULLS FIRST;<br><br>/*------+-------*<br> | x    | y     |<br> +------+-------+<br> | NULL | false |<br> | 9    | true  |<br> | 1    | true  |<br> *------+-------*/</pre><h3>QUALIFY Clause</h3><p>The QUALIFY clause filters the results of window functions. A window function is required to be present in the QUALIFY clause or the SELECT list.</p><p>Only rows whose bool_expression evaluates to TRUE are included. Rows whose bool_expression evaluates to NULL or FALSE are discarded.</p><pre>SELECT<br>  item,<br>  RANK() OVER (PARTITION BY category ORDER BY purchases DESC) as rank<br>FROM Produce<br>WHERE Produce.category = &#39;vegetable&#39;<br>QUALIFY rank &lt;= 3<br><br>/*---------+------*<br> | item    | rank |<br> +---------+------+<br> | kale    | 1    |<br> | lettuce | 2    |<br> | cabbage | 3    |<br> *---------+------*/<br><br><br>SELECT item<br>FROM Produce<br>WHERE Produce.category = &#39;vegetable&#39;<br>QUALIFY RANK() OVER (PARTITION BY category ORDER BY purchases DESC) &lt;= 3<br><br>/*---------*<br> | item    |<br> +---------+<br> | kale    |<br> | lettuce |<br> | cabbage |<br> *---------*/</pre><h3>SET Operators</h3><p>Set operators combine or filter results from two or more input queries into a single result set.</p><h4>UNION</h4><p>The UNION operator returns the combined results of the left and right input queries. Columns are matched according to the rules described previously and rows are concatenated vertically.</p><pre>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[1, 2, 3]) AS number<br>UNION ALL<br>SELECT 1;<br><br>/*--------+<br> | number |<br> +--------+<br> | 1      |<br> | 2      |<br> | 3      |<br> | 1      |<br> +--------*/<br><br><br>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[1, 2, 3]) AS number<br>UNION DISTINCT<br>SELECT 1<br>UNION DISTINCT<br>SELECT 2;<br><br>/*--------+<br> | number |<br> +--------+<br> | 1      |<br> | 2      |<br> | 3      |<br> +--------*/<br><br><br>SELECT 1 AS one_digit, 10 AS two_digit<br>UNION ALL<br>SELECT 20 AS two_digit, 2 AS one_digit;<br><br>-- Column values are matched by position and not column name.<br>/*-----------+-----------+<br> | one_digit | two_digit |<br> +-----------+-----------+<br> | 1         | 10        |<br> | 20        | 2         |<br> +-----------+-----------*/<br><br><br>SELECT 1 AS one_digit, 10 AS two_digit<br>UNION ALL BY NAME<br>SELECT 20 AS two_digit, 2 AS one_digit;<br><br>-- Column values now match.<br>/*-----------+-----------+<br> | one_digit | two_digit |<br> +-----------+-----------+<br> | 1         | 10        |<br> | 2         | 20        |<br> +-----------+-----------*/<br></pre><h4>INTERSECT</h4><p>The INTERSECT operator returns rows that are found in the results of both the left and right input queries.</p><pre>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[1, 2, 3, 3, 4]) AS number<br>INTERSECT DISTINCT<br>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[2, 3, 3, 5]) AS number;<br><br>/*--------+<br> | number |<br> +--------+<br> | 2      |<br> | 3      |<br> +--------*/<br><br><br>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[1, 2, 3, 3, 4]) AS number<br>INTERSECT DISTINCT<br>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[2, 3, 3, 5]) AS number<br>INTERSECT DISTINCT<br>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[3, 3, 4, 5]) AS number;<br><br>/*--------+<br> | number |<br> +--------+<br> | 3      |<br> +--------*/<br><br>WITH<br>  NumbersTable AS (<br>    SELECT 1 AS one_digit, 10 AS two_digit<br>    UNION ALL<br>    SELECT 2, 20<br>    UNION ALL<br>    SELECT 3, 30<br>  )<br>SELECT one_digit, two_digit FROM NumbersTable<br>INTERSECT DISTINCT<br>SELECT 10 AS two_digit, 1 AS one_digit;<br><br>-- No intersecting values detected because columns aren&#39;t recognized as the same.<br>/*-----------+-----------+<br><br> +-----------+-----------*/<br><br><br>WITH<br>  NumbersTable AS (<br>    SELECT 1 AS one_digit, 10 AS two_digit<br>    UNION ALL<br>    SELECT 2, 20<br>    UNION ALL<br>    SELECT 3, 30<br>  )<br>SELECT one_digit, two_digit FROM NumbersTable<br>INTERSECT DISTINCT BY NAME<br>SELECT 10 AS two_digit, 1 AS one_digit;<br><br>/*-----------+-----------+<br> | one_digit | two_digit |<br> +-----------+-----------+<br> | 1         | 10        |<br> +-----------+-----------*/</pre><h4>EXCEPT</h4><p>The EXCEPT operator returns rows from the left input query that aren&#39;t present in the right input query.</p><pre>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[1, 2, 3, 3, 4]) AS number<br>EXCEPT DISTINCT<br>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[1, 2]) AS number;<br><br>/*--------+<br> | number |<br> +--------+<br> | 3      |<br> | 4      |<br> +--------*/<br><br>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[1, 2, 3, 3, 4]) AS number<br>EXCEPT DISTINCT<br>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[1, 2]) AS number<br>EXCEPT DISTINCT<br>SELECT * FROM UNNEST(ARRAY&lt;INT64&gt;[1, 4]) AS number;<br><br>/*--------+<br> | number |<br> +--------+<br> | 3      |<br> +--------*/</pre><h3>LIMIT and OFFSET Clause</h3><p>Limits the number of rows to return in a query. Optionally includes the ability to skip over rows.</p><pre>SELECT *<br>FROM UNNEST(ARRAY&lt;STRING&gt;[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]) AS letter<br>ORDER BY letter ASC LIMIT 2;<br><br>/*---------*<br> | letter  |<br> +---------+<br> | a       |<br> | b       |<br> *---------*/<br><br>SELECT *<br>FROM UNNEST(ARRAY&lt;STRING&gt;[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]) AS letter<br>ORDER BY letter ASC LIMIT 3 OFFSET 1;<br><br>/*---------*<br> | letter  |<br> +---------+<br> | b       |<br> | c       |<br> | d       |<br> *---------*/</pre><h3>WITH Clause</h3><p>A WITH clause contains one or more common table expressions (CTEs). A CTE acts like a temporary table that you can reference within a single query expression.</p><p>In this example, a WITH clause defines two non-recursive CTEs that are referenced in the related set operation, where one CTE is referenced by each of the set operation&#39;s input query expressions:</p><pre>WITH subQ1 AS (SELECT SchoolID FROM Roster),<br>     subQ2 AS (SELECT OpponentID FROM PlayerStats)<br>SELECT * FROM subQ1<br>UNION ALL<br>SELECT * FROM subQ2</pre><p>You can break up more complex queries into a WITH clause and WITH SELECT statement instead of writing nested table subqueries. For example:</p><pre>WITH q1 AS (my_query)<br>SELECT *<br>FROM<br>  (WITH q2 AS (SELECT * FROM q1) SELECT * FROM q2)</pre><p>Reference</p><p><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#except_example">Query syntax | BigQuery | Google Cloud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87ad9cfb74ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encrypting and Decrypting PGP Files with Python]]></title>
            <link>https://atul-sutar.medium.com/encrypting-and-decrypting-pgp-files-with-python-6c470b2df4a8?source=rss-9079fe4063cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c470b2df4a8</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[pgpencryption]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pypy]]></category>
            <category><![CDATA[decryption]]></category>
            <dc:creator><![CDATA[Atul Sutar]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 17:40:15 GMT</pubDate>
            <atom:updated>2026-09-15T07:05:07.597Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s blog, I’ll guide you through the process of encrypting and decrypting PGP (Pretty Good Privacy) files using Python. This encryption method provides strong security for your sensitive data. Below, you’ll find code snippets for both the encryption and decryption scripts, along with the necessary requirements for your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ctfy_N1jIuTOWCIlhd_MSg.png" /></figure><p><strong>Code Snippets</strong></p><p>Below are the code snippets for the encryption and decryption scripts:</p><ul><li><strong>Encrypter</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPKRkIda0zSB6vE-EItZdQ.png" /><figcaption>encrypter.py</figcaption></figure><ul><li><strong>Decrypter</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pXi0P5AJizDNKfp48Ya-w.png" /><figcaption>decrypter.py</figcaption></figure><ul><li><strong>Requirements</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*L4Jegpc28AEr4F36i9_P1w.png" /><figcaption>requirements.txt</figcaption></figure><p>Please ensure you have these dependencies installed in your environment before running the scripts.</p><p><strong>Important Note</strong></p><p>The PGP keys provided in the code are sample keys. It’s crucial to generate your own PGP key pair and update the key names in the code accordingly.</p><p><strong>Instructions</strong></p><ol><li>Generate your PGP key pair and place them in the pgp_keys directory.</li><li>Put the files you want to encrypt or decrypt in the input_files folder.</li><li>Run the respective script (encrypter.py or decrypter.py) based on the operation you want to perform.</li><li>Once the script has executed successfully, check the output in the output_files directory. Note that the decrypter script will prompt for a passphrase.</li></ol><p><strong>Conclusion</strong></p><p>I hope this guide has been helpful in understanding how to encrypt and decrypt PGP files using Python. For a detailed walk through and access to the complete code, please visit my GitHub repository <a href="https://github.com/atul-sutar/PyEncryptDecrypt">here</a>.</p><p>Thank you for reading, and see you in the next blog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c470b2df4a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Election Results: Python Script for 2024 Parliamentary Election]]></title>
            <link>https://atul-sutar.medium.com/real-time-election-results-python-script-for-2024-parliamentary-election-b8245652c65e?source=rss-9079fe4063cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8245652c65e</guid>
            <category><![CDATA[rich]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Atul Sutar]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 11:32:51 GMT</pubDate>
            <atom:updated>2026-09-15T07:03:11.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blJcu-c4kKtMB1kmuPXz4A.png" /></figure><p>Hello Everyone,</p><p>Recently, on June 4th, 2024, the election results were announced for the General Election to Parliamentary Constituencies. The results are available on the government website <a href="https://results.eci.gov.in/PcResultGenJune2024/index.htm">here</a>.</p><p>When I saw the results, I got an idea for a simple and fun Python project. In this blog, I’m sharing a script I wrote to fetch the election results from the website and display them in a tabular format, sorted by seats won. The script automatically refreshes the data every 5 seconds.</p><p>For this project, I used the Python rich, bs4, and requests modules. The tabular results look great and are easy to read.</p><h4>Code Snippet:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*po2lQnu_hAUb46Pq0K2MAg.png" /><figcaption>Fetch Results Code (main.py)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*k8yRAyD_WGTUYaSbkeYwhg.png" /><figcaption>Requirements file (requirements.txt)</figcaption></figure><h4>Result Screenshot:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XkQINhpsn5OL2uY16xupiw.png" /><figcaption>Sample Table Screenshot 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0v8bFQLygsTIWcv2Jlz4g.png" /><figcaption>Sample Table Screenshot 2</figcaption></figure><p>click <a href="https://github.com/atul-sutar/parlimentary-election-june-2024-python-realtime-script/tree/main">here</a> for GitHub repository.</p><p>I hope you learn something new from this project. I enjoyed working with the bs4 and rich modules, which are excellent for web scraping and terminal styling.</p><p>Thank you, and see you in the next blog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8245652c65e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Fetch Data From The Looker Dashboard Using The Looker API]]></title>
            <link>https://atul-sutar.medium.com/python-fetch-data-from-the-looker-dashboard-using-the-looker-api-f0624f75b0ec?source=rss-9079fe4063cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0624f75b0ec</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[looker]]></category>
            <dc:creator><![CDATA[Atul Sutar]]></dc:creator>
            <pubDate>Wed, 01 May 2024 16:50:56 GMT</pubDate>
            <atom:updated>2026-09-15T07:01:44.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Rar7JWZG0YbKjqlJUhR0A.png" /><figcaption>Streamlining Data Extraction from Looker Dashboards Using Python</figcaption></figure><p>In this guide, we’ll walk through the process of extracting data from Looker dashboards using Python. Before diving into the code, it’s crucial to set up the necessary credentials and environment properly to ensure a secure and efficient workflow.</p><p><strong>1. Generating Client Credentials from Looker Admin Section:</strong> Begin by accessing the Looker Admin section to generate client credentials. Obtain the client ID and client secret from here, which will be used for authentication in the subsequent steps.</p><p><strong>2. Note the Dashboard ID:</strong> Identify the specific dashboard from which you want to extract data and make a note of its dashboard ID. This ID will be used to access the desired dashboard programmatically.</p><p><strong>3. Writing the Python Code:</strong> Create a Python script file or simply copy and paste the provided code snippets into your preferred text editor. The code will interact with Looker’s API to authenticate and fetch data from the designated dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ha83ChwvnHSW4o6fMiKvxw.png" /><figcaption>Looker API Code (main.py)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*5iyXN8m-EgswqgPoqrK9yA.png" /><figcaption>Requirements (requirements.txt)</figcaption></figure><p><strong>4. Handling Secrets Securely:</strong> It’s essential not to hard-code any sensitive information, such as the client ID and client secret, directly into the code. Instead, use best practices like storing secrets in environment variables or prompting the user for input during runtime.</p><p><strong>5. Dependency Resolution:</strong> Ensure that all required dependencies, such as the pandas and requests modules, are installed. You can install these dependencies using pip with the command “pip install &lt;module_name&gt;”.</p><p><strong>6. Running the Script:</strong> After setting up the credentials, environment, and resolving dependencies, you’re ready to execute the script. Simply run the Python file, and it will extract the data from the specified Looker dashboard.</p><p>By following these steps, you can seamlessly integrate Looker’s powerful data visualization and analytics capabilities into your Python-based workflows, enabling streamlined data extraction and analysis. Remember to always prioritize security and best practices when handling sensitive information and interacting with external APIs.</p><p>For GitHub repository link click <a href="https://github.com/atul-sutar/Streamlining-Data-Extraction-from-Looker-Dashboards-Using-Python">here</a>.</p><p>If you find this article helpful don&#39;t forget to like, comment and share.</p><p><strong>Reference </strong>— <a href="https://developers.looker.com/api/explorer/4.0/">https://developers.looker.com/api/explorer/4.0/</a></p><p>Thank you for reading, and see you in the next blog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0624f75b0ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Cloud-Run Build and Deploy Shell Script]]></title>
            <link>https://atul-sutar.medium.com/simple-cloud-run-build-and-deploy-shell-script-6e5bc339ff74?source=rss-9079fe4063cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e5bc339ff74</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[deploy]]></category>
            <category><![CDATA[shell-script]]></category>
            <category><![CDATA[cloudrun]]></category>
            <dc:creator><![CDATA[Atul Sutar]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 13:15:11 GMT</pubDate>
            <atom:updated>2026-09-15T07:00:40.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRflG_hKcUFtxbUuj9qlww.png" /><figcaption>Cloud shell code to deploy to cloud run service image</figcaption></figure><p>This is a shell script to build a container image and deploy it to Cloud-Run. This is my personal script, which I used to run from the GCP Cloud shell to build and deploy container images.</p><p>It is a quick and dirty script you can use to deploy code.</p><p>It will build and deploy the service and tag you specify. Give it appropriate executable permissions and store it in your shell path.</p><h4>Prerequisites :</h4><ol><li>A cloud-run service has already been created with some sample container images.</li><li>The script should be run from the directory where you stored the Dockerfile or code.</li></ol><h4>Code Snippet:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfnyMAuSTXDQJF4YDK0CFg.png" /><figcaption>Deploy Bash Script (deploy.sh)</figcaption></figure><h4>Usage :</h4><ol><li>Move into the directory where the code you want to deploy is.</li><li>Run the command as shown below, passing the first argument as the service name and tag name, separated by a colon.</li></ol><pre>deploy cloud-run-service:tag-here</pre><p>Above code and details can be found on my GitHub page : <a href="https://github.com/atul-sutar/Simple-CloudRun-Build-and-Deploy-Shell-Script">github-page</a></p><p>I welcome any suggestions.</p><p>Thank you for reading, and see you in the next blog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e5bc339ff74" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>