Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I need to find out the average time in which an event starts. The start time is recorded in DB in startDate column. ``` | StartDate | |=====================| |2015/04/10 3:46:07 AM| |2015/04/09 3:47:37 AM| |2015/04/08 3:48:07 AM |2015/04/07 3:43:44 AM| |2015/04/06 3:39:08 AM| |2015/04/03 3:47:50 AM| ``` So ...
Demo: <http://sqlfiddle.com/#!9/33c09/3> Statement: ``` select TIME_FORMAT(avg(cast(startDate as time)),'%h:%i:%s %p') as avg_start_date from demo ``` Setup: ``` create table demo (startDate datetime); insert demo (startDate) values ('2015-04-10 3:46:07'); insert demo (startDate) values ('2015-04-09 3:47:37'); ins...
Firstly you have to extract your datetime format to contain only time so that you can use an aggregate function on it. This is done by casting it to type `TIME`. Then you can use built-in aggregate function `AVG()` to achieve your goal and grouping to get average start date for every day you have in your table. This i...
How to find average on a timestamp column
[ "", "mysql", "sql", "date", "" ]
![Example](https://i.stack.imgur.com/2iU0P.jpg) when a row of ID is void, it will not show the cc\_type, but I need get the cc\_type for those void rows. ``` CASE WHEN CC_TYPE = 'Credit' OR Voided = 'Yes' THEN 'Credit' WHEN CC_TYPE = 'Debit OR Voided = 'Yes' THEN 'Debit' END ``` Obviously, this approach wouldn'...
You can use a window function: ``` SELECT id, Name, MAX(CC_Type) OVER (PARTITION BY id, name) AS CC_Type, Voided FROM yourtable ```
this worked for me: ``` create table result as select a.id,a.name,b.cc_type,a.voided from (select id, name,voided from table1) as a inner join (select distinct id, cc_type from table1 where cc_type ne "") as b on a.id = b.id; quit; ```
Get data based on other row
[ "", "sql", "sql-server-2012", "" ]
I want to get the number of unique mobile phone entries per day that have been logged to a database and have never appeared in the log. I thought it was a trivial query but shock when the query took 10 minutes on a table with about 900K entries. A sample Select is getting the number of unique mobile phones that were lo...
A `NOT IN` can be rewritten as a `NOT EXISTS` query which is very often faster (unfortunately the Postgres optimizer isn't smart enough to detect this). ``` SELECT COUNT(DISTINCT l1.mobile_number) FROM log_entries as l1 WHERE l1.created_at >= '2015-04-09 00:00:00' AND l1.created_at <= '2015-04-09 23:59:59' AND ...
I tend to suggest transforming `NOT IN` into a left anti-join (i.e. a left join that only keeps the left rows that do *not* match the right side). It's complicated somewhat in this case by the fact that it's a self join against two distinct ranges of the same table, so you're really joining two subqueries: ``` SELECT ...
Is there a way to make an SQL NOT IN query faster?
[ "", "sql", "postgresql", "" ]
For a small project, I am creating an entity relationship diagram for a simple stock-tracking app. **User Story** Products are sold by product suppliers. Products are ordered by an office and delivered to them. One or more deliveries may be required to full-fill an order. These products ordered by this office are in ...
This is a bit of an odd structure. Normally the way I would handle this wouldn't be with a daisy-chain structure that you have here, but would in turn use some sort of transaction-based system. The way I'd handle it is to have everything off of `order`, and `have one-to-many` relationships off of that. For instance, ...
![enter image description here](https://i.stack.imgur.com/t076F.png)![I have tried to create an ERD for you. Its very easy to understand. You only need to have one table between Delivery and Branch. Once a delivery is arrived against an order, the office will assign it to any branch by creating a record. That delivery ...
ER Diagram - Showing Deliveries to Office and to its Branches
[ "", "sql", "entity-relationship", "erd", "" ]
I've a problem with this part using Postgresql 9.4 where I need that the program only shows `sum(v.price) > 1000` but if I put `total > 1000` in where conditions says me that total doesn't exists and doesn't let me put `sum(v.price)` because it's not possible to do this kind of operations in this section. The creation...
Add `Having sum(v.price) > 1000` after `group by`: ``` SELECT p.name, p.address, p.city, sum(v.price) as total FROM VISIT v JOIN PATIENT p ON p.Pat_Number = v.Pat_Number WHERE Date(Visit_Date) < '01/01/2012' GROUP BY p.name, p.address, p.city, p.Pat_Number, v.Pat_Number HAVING ...
The conditions in the `WHERE` part of the query apply at each individual row. You can't use aggregate functions there. There is a similar functionality for groups called `HAVING`. `HAVING` is like `WHERE`, but the conditions are applied per group. So adding `HAVING sum(v.price) > 1000` to the query will filter only tho...
How to us an aggregated value in the where clause
[ "", "sql", "postgresql", "" ]
For example, I have simple SQL: ``` select product.name from products; ``` In my table I have 2 products: wheel, steering wheel. So my result is: ``` wheel steering wheel ``` How to get quoted result if the result has more than 1 word ?: ``` wheel "steering wheel" ``` I tried to use `quote_literal` function but ...
What about: ``` SELECT CASE WHEN (product.name LIKE '% %') THEN quoted_ident(product.name) ELSE product.name END FROM products; ```
use this: ``` SELECT name FROM products WHERE position(' ' in name)= 0 union SELECT '"'|| name ||'"' FROM products WHERE position(' ' in name)<>0 ``` Here is a [sqlfiddle](http://sqlfiddle.com/#!9/1a3dd/18)
Return quoted data from SQL query result only if needed
[ "", "sql", "postgresql", "" ]
I am stuck at a certain point with my select queries. I need to find from the table 'patient' a cellphone number that has a matching pair with the other patients cellphone number (if that makes any sense). at the moment I got this insert values from the table patient: ``` insert into patient values(1022010201, 88.2, ...
I have found the awnser to my own question. The result that I was looking for is this: ``` TELEFOONNR BSN -------------------- ---------- 676762516 1022010201 676762516 182704726 ``` This was possible due the following query: ``` select telefoonnr, bsn from patient where tel...
Try this: ``` select telefoonnr,count(telefoonnr) from patient group by telefoonnr having count (telefoonnr) > 1; ``` This is like finding duplicates in your table. So the above query will give you the `telefoonnr` along with `count` and other details from your table.
SQL SELF-JOIN with Oracle 11G - Finding a patient who has the same telephone number
[ "", "sql", "join", "oracle11g", "self-join", "" ]
I am using *Oracle SQL* and am having trouble updating a large amount of specific records from my `CTRL_NUMBER` *table*. Currently, when I want to only update one record, the following expression works: ``` UPDATE STOCK SET PCC_AUTO_KEY=36 WHERE CTRL_NUMBER=54252 ``` But, since I have *over 1,000 records to update*, ...
In your second `Update` command, you have: ``` WHERE CTRL_NUMBER=54252 AND CTRL_NUMBER=58334 ``` *My question*: is it possible for a field to have tow values at a same time in a specific record? of course no. If you have a `range` of values for `CTRL_NUMBER` and you want to update your table on base of them you can ...
Use the IN clause - ``` UPDATE STOCK SET PCC_AUTO_KEY=36 WHERE CTRL_NUMBER IN (54252, 58334) ``` Your statement is trying to update where CTRL\_NUMBER is 54252 AND 58334, but it can only be one of those at a time. If you changed your statement to ``` UPDATE STOCK SET PCC_AUTO_KEY=36 WHERE CTRL_NUMBER=54252 OR CTRL_N...
How do I update multiple records under one "Where" clause? (Oracle SQL)
[ "", "sql", "oracle", "where-clause", "" ]
I have created two tables one employee table and the other is department table .Employee table has fields `EmpId , Empname , DeptID , sal , Editedby and editedon` where `EmpId` is the primary key and `Dept` table has `DeptID` and `deptname` where `DeptID` is the secondary key. I want the SQL query to show names of em...
Use `INNER JOIN`: ``` SELECT E.empname FROM Employee E INNER JOIN department D ON E.DeptID=D.DeptID WHERE D.DeptID = '1' ```
Is this what you need? ``` SELECT EmpName FROM Employee WHERE DeptID = 1 ```
SQL query to find names of employees belonging to particular department
[ "", "mysql", "sql", "sql-server", "" ]
I have the following query which selects the top 3 records per category. At the moment it limits the records to 9. However, this is not right because if I limit the number to 8 the last subcategory loses one record from display. I want to limit the records per SubCategories queried number i.e. 3 subcategories only wit...
Do you mean something like: ``` SELECT * FROM (SELECT TOP(3) * FROM tSubCategory) c CROSS APPLY ( SELECT TOP(3) * FROM tProduct p WHERE c.SubCategoryID = p.SubCategoryID ORDER BY p.ProductID DESC ) x; ``` ...where I've based just wrapped your tSubCategory into a subquery to limit it to just three row...
This looks like an example for CROSS APPLY as mention by Rob Farley here: <http://blogs.lobsterpot.com.au/2011/04/13/the-power-of-t-sqls-apply-operator/> For this particular query, you would want to selct tthe top 3 subcategory rows and then use OUTER APPLY to append that to each product row. You will not be able to u...
Selecting top x categories with their top x products
[ "", "sql", "sql-server", "" ]
On a SQL Server 2008 I have a view `revenue` with the following schema: ``` +----------------------------+  | id | year | month | amount |  +----------------------------+  |  1 | 2014 |    11 |    100 |  |  2 | 2014 |    12 |   3500 |  |  3 | 2014 |    12 |     90 |  |  4 | 2015 |     1 |   1000 |  |  5 | 2015 |     2...
First off, the conversion error happens because there is no February 31st. I changed it to February 28th in the sample below. Since your table contains millions of rows, you're best off avoiding any conversions or calculations on the data in the table. Instead, convert the input to a format which matches your table. T...
You can do an integer comparison for your year month: ``` SELECT id, yr, month, amount FROM Magazines WHERE yr*100 + month >= 201412 AND yr*100 + month <= 201503 ``` This will not return your year month as a date however. Is this a requirement?
filter date records
[ "", "sql", "sql-server", "date", "between", "" ]
I hope you all can help me, it's been 2 days WITH a MuleSoft(MS) Guru by my side and we cannot figure this issue out. Simply put, we cannot connect to a SQL Server database. I am using a `Generic_Database_Connectory` with the following information: * URL: `jdbc:jtds:sqlserver://ba-crmdb01.ove.local:60520;Instance=CRM;...
This is how I used to configure and it works for me.. you can try this example :- ``` <db:generic-config name="Generic_Database_Configuration" url="jdbc:sqlserver://ANIRBAN-PC\\SQLEXPRESS:1433;databaseName=MyDBName;user=sa;password=mypassword" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriv...
If your test connection works fine, there should be no issues with your DB connection. Please post you config XML and that will help identifying the issue.
MuleSoft and SQL Server DB connection failure
[ "", "sql", "sql-server", "mule", "" ]
I have three tables in Mariadb ``` sensor +---------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------------+-------------+------+-----+---------+-------+ | name | varchar(64) | NO | PRI | NULL | | | reload_time | int(11)...
MariaDB and MySQL have the GROUP\_CONCAT() function to accomplish this task: ``` SELECT service_name, GROUP_CONCAT(sensor_name ORDER BY sensor_name) AS sensors FROM sensor_common_service GROUP BY service_name HAVING sensors='humidity,temperature' ``` <http://sqlfiddle.com/#!9/2f574/1>
Note that `IN` gives you an `OR` semantics when you need an `AND` semantics. Basically if you need all 3 sensors present, you need 3 joins, each representing a separate sensor. Something along the lines of ``` select * from common_service cs where exists (select 1 from sensor_common_service scs where s...
sql query with an specific cardinality (many to many)
[ "", "sql", "count", "mariadb", "" ]
While updating data in a table1 with `inner join` returning `O row updated`, both the table are in different database. I got alternate method to update this, but I don't why my `INNER JOIN` query gone wrong. **Not working with inner join** ``` UPDATE DB1.table1 SET t1.column3='value3' from DB1.table1 t1 INNER JOIN...
You have some syntax error in your statement. Use alias in SET and UPDATE part or use TableName, don't mix: ``` UPDATE t1 SET column3='value3' from DB1.table1 t1 INNER JOIN DB2.table2 t2 on t1.column2=t2.column2 WHERE (t1.column1 = 'value1') AND (t2.column3 = 'value3') ```
in your first query which does not works you have: ``` UPDATE DB1.table1 SET t1.column3='value3' . . . ``` you mentioned the actual name of the table for `update` but in `set` statement you have used the `alias` so there is a confusion. and in second one you told: ``` UPDATE DB1.table1 SET column3= ... ``` you ha...
update query with inner join [0 rows updated]
[ "", "sql", "sql-server", "sql-server-2008", "sql-update", "inner-join", "" ]
Can someone explain the performance difference between these 3 queries? `concat()` function: ``` explain analyze select * from person where (concat(last_name, ' ', first_name, ' ', middle_name) like '%Ива%'); Seq Scan on person (cost=0.00..4.86 rows=1 width=15293) (actual time=0.032..0.140 rows=6 loops=1) Filte...
While not a concrete answer, the following might help you to reach some conclusions: 1. Calling `concat` to concatenate the three strings, or using the `||` operator, results in postgres having to allocate a new buffer to hold the concatenated string, then copy the characters into it. This has to be done for each row....
What you have observed so far is interesting, but only a minor cost overhead for concatenating strings. The **much more important** difference between these expressions does not show in your minimal test case without indexes. The first two examples are not [**sargable**](https://dba.stackexchange.com/a/217983) (unles...
Query performance with concatenation and LIKE
[ "", "sql", "postgresql", "pattern-matching", "concatenation", "postgresql-performance", "" ]
What is the difference between these query ``` SELECT A.AnyField FROM A LEFT JOIN B ON B.AId = A.Id LEFT JOIN C ON B.CId = C.Id ``` and this another query ``` SELECT A.AnyField FROM A LEFT JOIN ( B JOIN C ON B.CId = C.Id ) ON B.AId = A.Id ```
Original answer: They are not the same. For example `a left join b left join c` will return a rows, plus b rows even if there are no c rows. `a left join (b join c)` will never return b rows if there are no c rows. Added later: ``` SQL>create table a (id int); SQL>create table b (id int); SQL>create table c (id i...
The first query is going to take ALL records from table `a` and then only records from table `b` where `a.id` is equal to `b.id`. Then it's going to take all records from table `c` where the resulting records in table `b` have a `cid` that matches `c.id`. The second query is going to first JOIN `b` and `c` on the `id`...
Differences between forms of LEFT JOIN
[ "", "sql", "" ]
I am trying to use the following code to run a different `join` query, based on a `CASE` statement. So if the `customer CLI` is equal to `84422881` I want it to join based on the `[Extenstion]` field and if the condition is not met i.e. the `ELSE` then to join on `[Customer CLI]` ``` use VoiceflexBilling CASE WHEN [...
you can use the `case` statement in the `join condition`: ``` UPDATE [dbo].[MARU15_OWH07579_Calls] SET [dbo].[MARU15_OWH07579_Calls].[CustomerLookup] = CLIMapping.[customer id] FROM [BillingReferenceData].[dbo].[CLIMapping] INNER JOIN [VoiceflexBilling].[dbo].[MARU15_OWH07579_Calls] ON [BillingReferenceData].[dbo]...
Some comments on your query. First, `case` is an *expression*, not control flow. So, it belongs inside a query. Second, you can just use "regular" logic for this query. Third, table aliases would make the query much easier to write and to read: ``` UPDATE c SET c.[CustomerLookup] = CLIMapping.[customer id] FROM [Voi...
Different join/update based on case query
[ "", "sql", "sql-server", "join", "sql-update", "case", "" ]
I have two seperate tables which I want to join based on Dates. However, I don't want the dates in the tables to be equal to one another I want the date (and accompanying value) from one table to be joined with the next date *available* after that date in the second table. I've put an example of the problem below: Ta...
Since you want the next available date, and that might not necessarily be the following date (eg. date + 1) you'll want to use a correlated subquery with either `min` or `top 1`. This will give you the desired output: ``` ;WITH src AS ( SELECT Date, NextDate = (SELECT MIN(Date) FROM Table2 WHERE Da...
``` try this select [Table 1].Date,[Table 1].Value,[Table 2].date,[Table 2].Value from [Table 1] join [Table 1] on dateadd(dd,1,[Table 1].date) = [Table 2].date ```
SQL Join based on dates- Table2.Date=Next date after Table1.Date
[ "", "sql", "sql-server", "t-sql", "date", "join", "" ]
I have the below query which runs ok and returns the string `2,3`. `FN_GET_PLAN_UPGRADE_OPTIONS` is returning a `VARCHAR`. ``` SELECT FN_GET_PLAN_UPGRADE_OPTIONS(1); ``` Now when I add this function call into a WHERE clause using the IN operator it only returns the result where act\_id contains `2` and no results whe...
The query you want to run is this: ``` SELECT ... WHERE act_id IN (2,3) ``` but the query you are actually running is this: ``` SELECT ... WHERE act_id IN ('2,3') ``` because your function returns a STRING (not a list of values), and since you are comparing a string with a NUMBER (act\_id), MySQL will automatically...
You should use `find_in_set()`: ``` WHERE find_in_set(act_id, FN_GET_PLAN_UPGRADE_OPTIONS(1)) ``` In interprets the returned value, say `'1,2'` as a single string of length three -- rather than two different values.
MySQL Function Oddness When Using IN Operator
[ "", "mysql", "sql", "function", "" ]
Is it expected that when I test if a null value is **not** in a list, the result is always false. That is: ``` select 'Hello world' where null not in(1,2,3); ``` Don't select anything, because null not in(1,2,3) is false. I don't understand this, because the list(1,2,3) don't contain any undefined values(null) so ...
Actually `null not in (1,2,3)` returns `null`, not `false`, but it works *like* false a `where` clause (since it's not `true`). Null comparisons `(a = null)`, etc. always return `null`, and since `null not in (1,2,3)` is essentially the same as: `NOT (null = 1 OR null = 2 OR null = 3)` The return value will be `null...
Null is always a special case in SQL. See <http://www.postgresql.org/docs/8.3/static/functions-comparison.html> > The ordinary comparison operators yield null (signifying "unknown") > when either input is null. So `Null not In (...) will wield Null` You can always use a CASE WHEN to bypass this behavior. See <http:...
Why is null not in(1,2,3) false
[ "", "sql", "postgresql", "" ]
In Oracle SQL Developer when you right click into a query result and select export it brings up the Export Wizard. After selecting the format you want (in this case .xls) the default save as target is (for me)`C:\Documents and Settings\XXXXX\export.xls` What i would like is to change the default output file name from...
As discovered this is not currently possible but is currently down as a feature request with Oracle to be implemented if it gets enough attention from users. **Feature request:** **<https://apex.oracle.com/pls/apex/f?p=43135:7:114031166834052::NO:RP,7:P7_ID:41561>**
I know this is an old thread but I was looking for an answer to this, and wanted to share some information for anyone else who comes along. As far as I know you still can't set the *exact* text of the file name or add a timestamp to it, but if you change the "Save As" setting in the Export Wizard window (this can be m...
Oracle SQL Developer query result Export Wizard default output file name
[ "", "sql", "oracle", "oracle-sqldeveloper", "" ]
I have multiple set of data to insert at once ``` INSERT INTO MyTable VALUES ("John", "Doe", 1234567890, "employee", ""); INSERT INTO MyTable VALUES ("Susen", "Gupta", 1234567890, "leander"); INSERT INTO MyTable VALUES ("Karn", "Share", 1234567890, "employee", "home"); ``` I want to insert multiple rows in a single S...
[Multi-row insert](http://en.wikipedia.org/wiki/Insert_%28SQL%29#Multirow_inserts) has been part of the SQL standard since SQL-92, and many of the modern DBMS' support it. That would allow you to do something like: ``` insert into MyTable ( Name, Id, Location) values ('John', 123, 'Lloyds Office'...
Yes you can, but it depends on the SQL taste that you are using :) , for example in mysql, and sqlserver: ``` INSERT INTO Table ( col1, col2 ) VALUES ( val1_1, val1_2 ), ( val2_1, val2_2 ), ( val3_1, val3_2 ); ``` But in oracle: ``` INSERT ALL INTO Table (col1, col2, col3) VALUES ('val1_1', 'val1_2', 'val1_3') ...
Insert multiple rows of data in a single SQL statement
[ "", "sql", "insert", "sql-insert", "" ]
The below query gives me results for count greater than 70. ``` SELECT books.name, COUNT(library.staff) FROM (library INNER JOIN books ON library.staff = books.id) GROUP BY library.staff,books.id HAVING COUNT(library.staff) > 70; ``` How do I modify my query to get the result with the *maximum* count?
One method is `order by` and `limit`: ``` SELECT b.name, COUNT(l.staff) as cnt FROM library l INNER JOIN books b ON l.staff = b.id GROUP BY l.staff, b.name ORDER BY cnt DESC LIMIT 1; ``` I find it strange that you are grouping by two columns, but only one is in the `select`. However, if the query is working...
you can do like this ``` SELECT books.name, COUNT(library.staff) FROM (library INNER JOIN books ON library.staff = books.id) GROUP BY library.staff,books.id HAVING COUNT(library.staff) = (select max(library.staff) from library); ```
SQL - getting max value
[ "", "sql", "postgresql", "join", "count", "aggregate-functions", "" ]
I have a SQL Server 2008 table, and I need to select a running balance from it ``` TransDate Credit Debit Datasource ------------------------------------------ 2014-01-01 5000 NULL 3 2014-01-07 NULL 2000 3 2014-01-11 5000 NULL 3 2014-02-03 6000 NULL 4 2014-02-06 N...
You need to self join table. ``` CREATE TABLE Test ( TransDate DATE, Credit INT, Debit INT, ); INSERT INTO Test VALUES ('2014-01-01', 5000, NULL), ('2014-01-07', NULL, 2000), ('2014-01-11', 5000, NULL), ('2014-02-03', 6000, NULL), ('2014-02-06', NULL, 4000), ('2...
I would recommend to doing this: ## Data Set ``` CREATE TABLE Test1( Id int, TransDate DATE, Credit INT, Debit INT ); INSERT INTO Test1 VALUES (1, '2014-01-01', 5000, NULL), (2, '2014-01-07', NULL, 2000), (3, '2014-01-11', 5000, NULL), (4, '2014-02-03', 6000, NULL), (5...
Select running balance from table credit debit columns
[ "", "sql", "sql-server-2008", "select", "cumulative-sum", "" ]
I have two tables: 1. "Sessions" - it have int key identity, "session\_id" - varchar, "device\_category" - varchar and some other colums. There are 149239 rows. 2. Session\_events" - it have int key identity, "session\_id" - uniqueidentifier and some other fields. There are 3140768 rows there. This tables...
Deleting a huge bunch of data at once means that the DB engine has to do all of that in a single transaction. This means a huge overhead when you don't actually need that (e.g. you don't need to rollback the whole operation, or you don't care about consistency - you just want to delete everything, if it fails in the mi...
Why not use a left join? other alternative is to use EXISTS instead of IN: ``` DELETE FROM Session_events WHERE NOT EXISTS( SELECT 1 FROM Session WHERE Session.Session_Id = Session_events.Session_Id ) ```
Extremely long "Not In" request
[ "", "sql", "sql-server", "database", "performance", "query-performance", "" ]
I have a Table (let's say table) with 4 columns - ``` Product_ID, Designer, Exclusive, Handloom ``` ID is the primary key and other 3 columns have values 0 or 1. Eg - `0` in `Designer` means the product is not designer and `1` means it is designer. I want to write down a query to select 6 rows out of the given 16 r...
Is this going to be horribly slow? ``` select t1.Code, t2.Code, t3.Code, t4.Code, t5.Code, t6.Code from Table t1, Table t2, Table t3, Table t4, Table t5, Table t6 where t1.Code < t2.Code and t2.Code < t3.Code and t3.Code < t4.Code and t4.Code < t5.Code and t5.Code < t6.Code and t1.Designer + t2.Designer + ...
``` SELECT Product_ID, Designer, Exclusive, Handloom FROM table-name WHERE Designer <> 0 AND (Exclusive <> 0 OR Handloom <> 0) LIMIT 6 ; ```
MYSQL - Select rows fulfilling many count conditions
[ "", "mysql", "sql", "" ]
I want to figure out if a query result contains exactly some items. I explain: I have a profile\_stores table that contains the managed stores of each profile Let's say i have 5 profiles P1-> P5 and 4 stores s1 -> s4 and my table contains ``` profie | store ------------------ P1 | S1 P2 | S2 P3 | S...
`GROUP BY`-solution: ``` select profile from tablename group by profile having count(distinct store) = 2 and min(store) = 'S1' and max(store) = 'S2' ``` Alternative solution: ``` select profile from tablename t1 where not exists (select 1 from tablename t2 where t1.profile = t2.profile ...
``` SELECT DISTINCT profile FROM profile_stores WHERE profile IN (SELECT profile FROM profile_stores WHERE store = 'S1') AND profile IN (SELECT profile FROM profile_stores WHERE store = 'S2') AND profile NOT IN (SELECT profile FROM profile_stores WHERE store NOT IN ('S1','S2')) ``` Alternatively, use the lesser-kn...
How to figure out if a query result contains exactly some items
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
What are the best and the most efficient way of finding null values in multiple columns. For example: ``` Name Location Age Address Mike CLT 19 Null Null NY 28 Null ``` and so on... I just need to find out if there is any NULL value in any of these columns.
if you want to know if there are nulls in any column, this could be a good trick to generate an XML file from the rows containing those nulls; it should work for almost any table, just replace 'yourtable' with the name of the relevant table: ``` SELECT CAST ( (SELECT * FROM yourtable FOR XML path('x'),ELEMENTS XSINIL...
Check this query. Hope this gives you desired result. ``` Select * from YourTableName where Name is null or location is null or age is null or address is null ```
Finding Null values in multiple columns in SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I have 2 tables, `Table1 (Id, Name, Email)` and `Table2 (Id, ItemName, Price, IsShipping)`. I need to join them on `Id` columns, but `IsShipping` column has `NULL` values, I need to change `NULL` to `0`. For now I have: ``` SELECT Table1.Id, Table1.Name, Table1.Email, Table2.ItemName, Table2.Price, Table2.IsShipping ...
You can use [ISNULL](https://msdn.microsoft.com/en-us/library/ms184325.aspx) in following: > ISNULL replaces NULL with the specified replacement value. ``` SELECT t1.Id, t1.Name, t1.Email, t2.ItemName, t2.Price, ISNULL(t2.IsShipping, 0) -- Here you pass ISNULL FROM Table1 t1 JOIN Table2 t2 ON t1.Id =...
Use the ANSI standard function `coalesce()`: ``` SELECT t1.Id, t1.Name, t1.Email, t2.ItemName, t2.Price, coalesce(t2.IsShipping , 0) as IsShipping FROM Table1 t1 JOIN Table2 t2 ON t1.Id = t2.Id; ``` I also added table aliases. They make the query easier to write and to read.
How to select data from 2 tables and convert NULL to 0?
[ "", "sql", "sql-server", "" ]
EDIT: This is an example relation! I need it to work on a bigger relation so no workarounds! So I was given a simple task and at first I didn't see what could possibly be wrong and now I just don't understand why it doesnt work. Lets say I have a table of people and their friends and I want to select the ones who hav...
From the doc <http://www-01.ibm.com/support/knowledgecenter/SSGU8G_12.1.0/com.ibm.sqls.doc/ids_sqs_0162.htm> > The condition in the HAVING clause cannot include a DISTINCT or UNIQUE > aggregate expression. An work-around would be to have the count distinct in the select ``` SELECT person, count(distinct friend) as...
you need to write it like this ``` SELECT person FROM people WHERE relation = 'friend' GROUP BY person HAVING count(*) > 1; ```
How to have 'distinct' in having clause
[ "", "sql", "informix", "" ]
Hi I have the following code ``` SELECT entertainer_id, entertainer_groupname FROM casestudy_entertainer INNER JOIN casestudy_availability ON casestudy_entertainer.entertainer_id = CASESTUDY_AVAILABILITY.AVAILABILITY_ENTERTAINERID INNER JOIN casestudy_calendardates ON CASESTUDY_AVAILABILITY.AVAILIB...
You should try the lower case for the table/column identifiers(like in `from`/`inner join` clauses): ``` SELECT entertainer_id, entertainer_groupname FROM casestudy_entertainer INNER JOIN casestudy_availability ON casestudy_entertainer.entertainer_id = casestudy_availability.availability_entertainerid INNE...
This Error is caused by a special character in one of the columns of the database table. DBA will be able to help you.
SQL Queries "00904. 00000 - "%s: invalid identifier"
[ "", "sql", "oracle", "" ]
I would like to know how to replace the a part of a value which is stored into a columns named "keyword\_data" in the table "keyword". The values in the MySQL columns look like this: ``` a:5:{s:11:"{%KEYWORD%}";s:59:"keyword test 1";s:9:"{%PRICE%}";s:6:"279,99";s:12:"{%CATEGORY%}";s:6:"Camera";s:9:"{%IMAGE%}";s:61:"h...
Just do: ``` UPDATE keyword SET keyword_data = REPLACE( keyword_data , '?tag=mytag' , '&tag=mytag') WHERE keyword_data LIKE '%?tag=mytag%'; ``` [Working example!](http://sqlfiddle.com/#!9/26e1d/1) Also you should be really careful with this. Always make a copy of your database before you fool around with...
mysql provides a command called REPLACE. REPLACE has the following structure: ``` REPLACE(text, from_string, to_string) ``` This can be used in an update statement: ``` UPDATE keyword SET keyword_data = REPLACE(keyword_data, '?tag=mytag', '&tag=mytag'); ```
Search and replace part of string
[ "", "mysql", "sql", "" ]
I have 4 tables in my SQL Server 2008 database : * CONTACT * CONTACT\_DETAILS * PLANS * PLANS\_DETAILS Every record is recorded in `CONTACT` and `CONTACT_DATAILS` but a `CONTACT` can have 0, 1, 2 or more records in `PLANS`, Active or Cancelled. So I did this: ``` SELECT * from CONTACT as c left join PLANS as pp on...
The answer to your question is to move the condition on `pp` to the `on` clause. ``` SELECT * from CONTACT c inner join CONTACT_DETAILS cd on cd.DKEY = c.DKEY left join PLANS pp on pp.PKEY = c.PKEY AND PP.STATUS = 'Active' left join PLANS_DETAILS pd on pd.PDKEY = p.PDKEY WHERE c.KEY = '26...
Just add an `ORDER BY PP.STATUS DESC` and a `TOP 1` clause, and delete the `and PP.STATUS = 'Active'`, like this ``` SELECT TOP 1 * from CONTACT as c left join PLANS as pp on pp.PKEY = c.PKEY left join PLANS_DETAILS as pd on pd.PDKEY = p.PDKEY inner join CONTACT_DETAILS as cd on cd.DKEY = c.DKEY WHERE c.KEY = '100003...
Join questionn - Select must return only one record
[ "", "sql", "sql-server", "join", "" ]
so I have 3 tables, actor(id, name), movie (id,name,year) and casts(aid, mid) (which are actor id and movie id). My goal is to select all the actors who acted in a film before 1900 and also in a film after 2000. My query is ``` select a.id from actor a, movie m1, casts c1, movie m2, casts c2 where a.id = c1.aid = c2....
I assume the problem is the expression `a.id = c1.aid = c2.aid`. If I am not mistaken, this first compares `c1.aid` with `c2.aid` and then the boolean result with `a.id`. You could try this: ``` select a.id from actor a inner join casts c1 on c1.aid = a.id inner join casts c2 on c2.aid = a.id inner join movie m1 on ...
To get actors who were in films during two date ranges, use two subqueries. Something like this: ``` select yourFields from yourTables where actorId in (subquery to get actor id's for one date range) and actorId in (subquery to get actor id's for second date range) ``` You can work out the details.
sql list actors who acted in a film before 1900 and also in a film after 2000
[ "", "sql", "database", "sqlite", "select", "" ]
What I like to do is to pull a data set only for busy hour on every Friday for 1 year period. I have used the following query: ``` select to_char(datetimelocal,'DD/MM/YYYY HH24:MI:SS'), colA,colB,colC,colD from Schema_X.Table_Y where DATETIMELOCAL between '1-Apr-2014' and '1-Apr-2015' and to_char(datetimelocal,'...
As Jon said, Oracle can not zoom in to specific partitions because of how your where clause is expressed. If you want all fridays you have to give the sql engine specific days. This can be done by creation a table with all fridays you need or generating one on the fly. ``` -- generate table CREATE TABLE friday_table (...
Your query is filtering in stages, first by year then by day, then by time. That means that in principal any record could be counted; the system cannot easily zoom in on the partitions you need. You need to express the filter in terms of specific dates: ``` SELECT * FROM Tbl WHERE DateTimeLock >= DATE'2015-04-...
Oracle SQL pull data for a selected date from a table that is daily partitioned
[ "", "sql", "oracle", "overloading", "partition", "" ]
I want to join these two SQL select statements and get both results as a single result. ``` --1st select statement SELECT TA.DevID, TA.Task, TA.AssignDate, TA.DevStart,TA.TaskType, TA.EstimateTime, TA.Status, TA.DevFinish, TAKPI.actAsignTime, TAKPI.actTime, TAKPI.KPI FROM TT_TaskAssign TA INNER JOIN HR_EmployeeMaste...
remove `order by` from second query ``` SELECT T1.*, T2.* FROM (SELECT TA.DevID, TA.Task, TA.AssignDate, TA.DevStart,TA.TaskType, TA.EstimateTime, TA.Status, TA.DevFinish, TAKPI.actAsignTime, TAKPI.actTime, TAKPI.KPI FROM TT_TaskAssign TA INNER JOIN HR_EmployeeMaster1 EM on TA.DevID=EM.EmpNo INNER JOIN d...
As the error message sayed. `ORDER BY` is not allowed in subquery. If you need the `order by` clause you have to use it for the whole result of the `join`.
Join two SQL select statements and get both results in to single
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I'm trying to extract email addresses from an existing comments field and put it into its own column. The string may be something like this "this is an example comment with an email address of someemail@domain.org" or just literally the email itself "someemail@domain.org". I figure the best thing to do would be to fin...
You can search for `'@'` in the string. Then you get the string at the `LEFT` and `RIGHT` side of `'@'`. You then want to `REVERSE` the `LEFT` side and get first occurrence of `' '` then get the `SUBSTRING` from there. Then `REVERSE` it to get the original form. Same principle apply to the `RIGHT` side without doing `R...
I know wewesthemenace already answered the question, but his/her solution seems over complicated. Why concatenate the left and right sides of the email address together? I'd rather just find the beginning and the end of the email address and then use substring to return the email address like so: ## My Table ``` DECL...
Extract email address from string using tsql
[ "", "sql", "sql-server", "regex", "t-sql", "" ]
I need to create a view in PostgreSQL 9.4 about this table: ``` CREATE TABLE DOCTOR ( Doc_Number INTEGER, Name VARCHAR(50) NOT NULL, Specialty VARCHAR(50) NOT NULL, Address VARCHAR(50) NOT NULL, City VARCHAR(30) NOT NULL, Phone VARCHAR(10) NOT NULL, Salary DECIMAL(8,2) NOT NULL, ...
`DISTINCT ON` is a simple Postgres specific technique to get *one* winner per group. Details: * [Select first row in each GROUP BY group?](https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group/7630564#7630564) ``` CREATE VIEW top_specialty_doctors AS SELECT DISTINCT ON (specialty) ...
Here's a query that shows the best doctor by salary for each of the specialties: ``` with specialty_ranks as ( select Salary, name, specialty, rank() over ( partition by specialty order by salary desc ) as rank from DOCTOR where specialty in ('family and community', 'psychiatry', 'Rh...
create view selecting the max in one column related with another column
[ "", "sql", "postgresql", "max", "greatest-n-per-group", "sql-view", "" ]
table 1: ``` id 1 2 3 5 6 ``` table 2: ``` id 2 3 7 ``` I want only mismatch `id` from table 1 like my result should be `1,5,6`. Please help on this, thanks in advance.
Try this: ``` SELECT * FROM table1 WHERE id NOT IN (SELECT id FROM table2) ```
You can use `NOT IN` ``` select id from table1 where id not in (select id from table2) ```
i have two table find out only mismatch id
[ "", "sql", "" ]
I am trying to to reduce cost and size of a query I use regularly, it looks far too repetitive to be the most efficient way of doing things. A simplified representation can be seen below: ``` SELECT [Year], [Month], COUNT(CASE WHEN Type = 'Quotation' THEN clientID ELSE NULL END), COUNT(CASE WHEN ...
I think that is the recommended way to 'rotate' a table. Check this article from Microsoft -> <https://support.microsoft.com/en-us/kb/175574> Probably the cost is in the 'Type' column, maybe you can index that -> [How to create an index for a string column in sql?](https://stackoverflow.com/questions/9455568/how-to-c...
How about making a view by type ? (Quotation, purchase, etc). In that way, you can optimize view by view and make a join query to get what you want.
Repetitive CASE WHEN in Aggregate SQL SELECT Statements
[ "", "sql", "sql-server", "sql-server-2008", "case", "" ]
I need to write some SQL that will determine if the current month is based on a quarter from a specified date. If I give it '2015-04-09', the function should determine if the month is equal to 1, 4, 7, or 10. If I give it '2015-05-09', it will be 2, 5, 8, 11. Etc... It would work best if the entire solution is self c...
It looks like you want to know when this expression is true: ``` (mod(EXTRACT(MONTH FROM SYSDATE()), 3)) = (mod(EXTRACT(MONTH FROM <input date>), 3)) ```
You can extract the month using `month()` and then use modulo arithmetic. Something like this: ``` select (case when mod(month($input) - month($thedate), 3) = 0 then 1 else 0 end) ```
Determine if month of date falls on a quarter of date
[ "", "mysql", "sql", "date", "" ]
I need to display the total amount of hours elapsed for an action within a month and the previous month before it like this: ``` ___________________________________________ | Rank | Action | Month | Prev Month | |------|----------|------------|------------| | 1 | Action1 | 580.2 | 200.7 | | 2 ...
I'm just revisiting this question after researching a bit more about SQL Server. A temporary table can be created from a query and then used inside another query - a *nested query* if you like. This way the results can `JOIN` together like through any other normal table without nasty `CASE` statements. This is also ...
i changed the values a bit since only one day is rather boring ``` INSERT INTO yourtable ([Action], [StartTime], [EndTime]) VALUES ('Action1', '2015-02-18 06:01:53', '2015-02-18 06:12:05'), ('Action1', '2015-02-18 06:22:16', '2015-02-18 06:25:33'), ('Action2', '2015-04-03 06:36:07', '2015-04-03 06:36:4...
SQL SUM hours between two dates & GROUP BY Column Name?
[ "", "sql", "sql-server", "datetime", "datediff", "" ]
I am struggling to get this query right. Every time I change it, it breaks something else. ``` SELECT products.id, products.name, COUNT(transactions.id) AS sales, IFNULL(SUM(cart.price_paid), 0) AS amount FROM products LEFT JOIN cart ON cart.product_id = products.id LEFT JOIN transactions ON cart.transaction_id = t...
A `product` table with a `user_id` column is pretty weird. I can see how a cart belongs to a user, but why would a product belong to a user? For your query, I suppose you'd like to sum the `price_paid` of sold carts only. Where a cart is considered sold if it has a completed transaction. You could do so like this: ``...
The IFNULL function should be used inside the SUM function. ``` Because NULL+10 is null not 10, IFNULL(NULL,0)+10 is 10 ``` Try This.. ``` SELECT products.id, products.name, COUNT(transactions.id) AS sales, SUM(IFNULL(cart.price_paid, 0)) AS amount FROM pr...
How to correct this SQL query? SUM with JOIN
[ "", "mysql", "sql", "" ]
I have the following table structure : **News** (Id\_news, news\_name) **Comments** (Id\_comment(PK),Id\_news(FK), comment) **Replies**(Id\_Reply(PK), Id\_Comment(FK), reply) --- I want to get the number of replies to comments in the news. This is the query I've tried. ``` SELECT COUNT(*) FROM (News INNER JOIN C...
As you have mentioned that you want to have a count of replies for any particular news which may or may not have any comment or reply. Here is my try ``` SELECT COUNT(Replys.Id_Reply) FROM NEWS LEFT JOIN Coments ON Coments.ID_News = Coments.Id_News AND NEWS.Id_News = {0} LEFT JOIN Replys ON Replys.Id_Comment = Com...
Try this.. ``` SELECT News.Id_news,COUNT(*) FROM News JOIN Comments ON News.Id_news = Commnets.Id_news JOIN Reply ON Commnets.Id_Comment = Reply.Id_Comment WHERE News.Id_news = {0} group by News.Id_news,Commnets.Id_Comment ```
SQL Server INNER JOIN with three tables
[ "", "sql", "asp.net", "sql-server", "" ]
Let's say I have a table that looks like, ``` id 2 2 3 4 5 5 5 ``` How do I get something like, ``` id count 2 2 3 1 4 1 5 3 ``` where the `count` column is just the count of each id in the `id` column?
You want to use the GROUP BY operation ``` SELECT id, COUNT(id) FROM table GROUP BY id ```
``` select id, count(id) from table_name group by id ``` or ``` select id, count(*) from table_name group by id ```
Count items in column SQL query
[ "", "sql", "sqlite", "" ]
So what I need to do is to select the maximum of column (and increment it with 1 each time) and if this value is null (which will be the case for the first occurence) I must return the constant 0 (which will be the max for the next occurence). My goal is to do something like this : ``` SELECT (Max(id) + 1) FROM my_ta...
The way your query is written, it will return two rows. One for the first query, and one after the union. If you only want a single row, you can just use the MAX() function. If the table is empty, the MAX() function returns null. An option you have then is to use COALESCE() in your select statement, which returns the ...
Try this ``` SELECT COALESCE(Max(id + 1), 0) FROM my_table WHERE id IS NOT NULL ```
SQL - select an increment value or return a constant
[ "", "mysql", "sql", "select", "null", "union", "" ]
Let's say I have a table like this: ``` OrderId | CustomerId | ProductName ====================================== 73 | 301 | Sponge 74 | 508 | Garbage Bag 75 | 301 | Spoon 76 | 301 | Bacon 77 | 508 | Dog treats ...
``` select customerId, count(*) from mytable group by customerId having count(*) >= 2 ```
If you need only `CustomerId` of those who have exactly one order in table (they exist once) then the following query groups customers and counts how many times they appear in a table (here showing only those who appear once, modify as you wish). ``` SELECT CustomerId FROM table GROUP BY 1 HAVING COUNT(*) = 1 ``` ...
SQL - find rows having n duplicate values
[ "", "sql", "" ]
I have a table with indexes of imported files, with dates and branches of each imported files. Now I need to do a consolidation of multiple branches, so, that I have to duplicate the information from some branches when we have holidays, so that the data is consistent, basically I need to fill these gaps with the lates...
you can use `outer join`, `subquery` and `cross join`: *Schema:* ``` create table tbl(rundate date, branch varchar(10), imported bool); insert into tbl values('2015-04-01', 'PL1', TRUE), ('2015-04-01', 'ES1', TRUE), ('2015-04-01', 'CZ4', TRUE), ('2015-04-02', 'PL1', TRUE), ('201...
You have to select all unique dates in one set, all unique branches in another - make a cartesian product of it - and then you can check for which combination you have a gap... this is what I mean: ``` CREATE TEMPORARY TABLE _matrix SELECT t1.rundate, t2.branch (SELECT DISTINCT rundate FROM yourtable) t1, (SELECT DIST...
Postgresql Fill Gaps - Matrix of latest available information for a given branch
[ "", "sql", "postgresql", "window-functions", "gaps-in-data", "" ]
I need to select top 20000 from my table that has several columns (number,color etc...) and i need to get the count of the red and the count of the blue from these 20000 in one query. I know i can get what i want if i insert the top 20000 in a temp table and then select count of the red from the temp table and then se...
You can use nested query: ``` select inner.color, count(*) from (select top 20000 [number], color from [profile]) inner group by inner.color ```
You can use `iif` : ``` select top 20000 [number] , sum(iif([color] = 'red', 1, 0) as red_count , sum(iif([color] = 'blue', 1, 0) as blue_count from [profile] group by [number] ``` or `case`: ``` select top 20000 [number] , sum(case when [color] = 'red' then 1 else 0 end) as red_count , sum(cas...
select 2 different count in sql server
[ "", "sql", "sql-server", "sql-server-2008", "count", "sql-server-2012", "" ]
I am looking to insert some values into a column based on the selection of a specific row. I have a table with columns a, b, c, and d. I want to insert the values 1, 2, and 3 into columns b, c, and d when column `a = X`. I cannot find how to do this. Toad for oracle is my platform and I am looking for SQL code.
You can either update them one at a time: ``` update mytable set b = 1 where a = X; update mytable set c = 2 where a = X; update mytable set d = 3 where a = X; ``` Or update them all in one go: ``` update mytable set b = 1,c = 2,d = 3 where a = X; ``` Alternatively, assuming 'a' is a primary key column or unique in...
You can use `INSERT INTO...SELECT` and give condition to your insert queries such as: ``` INSERT INTO table_name (b, c, d) VALUES (bValue, cValue, dValue) /* Select Condition */ WHERE a=1 ```
Insert Values into table of specific row
[ "", "sql", "oracle", "sql-insert", "" ]
I have an MS Access database with 40 similar tables. Only a couple are listed below for simplicity. I want to grab 3 cells of data from a row if the date in that row is yesterday. The data comes from some other employee's homebrew spreadsheets that they refuse to give up. So I can't change the column names or get them ...
Do you really need a where condition on each section of your union? Or do you just want the whole results filtered? ``` SELECT * FROM ( SELECT [Customer name],[$ Amount], [Quote Completed] FROM 1081 UNION SELECT [Customer name],[$ Amount], [Quote Completed] FROM 1145 UNION SELECT [Customer ...
You may need to use dateadd: ``` SELECT [Customer name],[$ Amount], [Quote Completed] FROM 1081 WHERE [Quote Completed] = DateAdd('d',-1, date()) ``` Added link: <http://www.techonthenet.com/access/functions/date/dateadd.php>
Why won't my "WHERE" statements work in sql?
[ "", "sql", "ms-access", "" ]
In a given Date Range I would like to get Name of the Month and End Date of the month. Based on the given values, I will different counts and calculate the final value. I can do it with CTE, But I dont have idea in how to it completely with CTE. I prefer one more way than doing it using CTE. Version of SQL 2008 R2, ...
Works on SLQ SERVER 2008+ ``` Declare @Start datetime Declare @End datetime Select @Start = '2014-08-08' Select @End = '2015-04-01' declare @day DATETIME = @Start declare @tab TABLE(MONTH_NAME varchar(20),LAST_DAY_OF_MONTH DATETIME) while @day <= @end begin INSERT INTO @tab SELECT DATENAME(...
For both 2012+ Or 2012- ``` DECLARE @Start DATETIME = '2014-08-08', @End DATETIME = '2015-04-01' SELECT DATENAME(MONTH, DATEADD(MONTH, a.number, @Start)) AS NameOfMonth ,EOMONTH(DATEADD(MONTH, a.number, @Start)) AS EndOfMonthForSQL2012Plus ,DATEADD(DAY, -1, DATEADD(MONTH, 1 + DATEDIFF(MONTH,...
How to get Month name and End Date of Month within a date rage
[ "", "sql", "sql-server", "sql-server-2008-r2", "sql-server-2012", "" ]
I'm a bit stuck with a stored procedure that is executing really slow. The stored procedure basically contains a query that uses an incoming parameter (in\_id) and is put in a cursor like this: ``` open tmp_cursor for select col1, col2, col3 from table1 tab where ((in_id is null) or (tab.id = in_id)); -- tab.id is t...
*Assuming that `in_id` is a query parameter - not a column name:* The query has to have only ONE exec plan, regardless of the input. So if you pass parameter `in_id` as NULL, then it is supposed to return ALL rows. If you pass non-NULL `in_id` is should return only a single PK value. So Oracle chooses the "worst poss...
> in\_id is null I have answered a similar question here <https://stackoverflow.com/a/26633820/3989608> Some facts about NULL values and INDEX: * Entirely NULL keys are not entered into a ‘normal’ B\*Tree in Oracle * Therefore, if you have a concatenated index on say C1 and C2, then you will likely find NULL values ...
Stored procedure SQL execution plan
[ "", "sql", "oracle", "sql-execution-plan", "" ]
I just wanted to know the best way I can use in Oracle query, to avoid updating a field , if that is unchanged? ``` Update xtab1 set xfield1='xxx' where xkey='123'; ``` In performance aspect what is best way , with which this update should not be invoked , if the existing value of xfield1 is 'xxx' . Option1 : > * s...
> Update xtab1 set xfield1='xxx' where xkey='123' and xfield1 <> 'xxx' The **filter predicate** is applied before doing the update. So, I would go with option 2 and **let Oracle do the job for you rather than doing it manually to first filter out the rows**. Also, it would be an overhead to do it in two different step...
I don't think there will be significant performance difference between the two options, as both will require looking up rows and performing comparison of the values. And I doubt other options such as pre-update triggers will yield better performance than your option 2. If you really wanted to know how the Oracle optim...
What is the best way in Oracle query, to avoid updating a field , if that is unchanged?
[ "", "sql", "oracle", "sql-update", "" ]
I'm wondering what is the best method to store generic classes in a database. For an easy illustration assume the following classes: ``` Interface IShape Center: Point Size: Point Color: Int Class Line : IShape (IShape Members...) LineWidth: Int Orientation: Int Class Circle: IShape (IShape Members...)...
The generic `List<IShape>` is something of a red herring here since it is nothing more than the representation of a one-to-many link, or perhaps a slice of a many-to-many link table; there is no uniquely generics-related mapping complexity in your question. There is really no single best practice here due to the depth...
Your option of number 2 stands out the most to me. At the place I work we have a database system that stores meta information about work flows; there is a central table that stores the basic workflow item information (ID, Item Name, Default Person Responsible, etc) and then each type of item has its own table that sto...
Database design for generics
[ "", "sql", "database", "generics", "database-design", "" ]
``` Column_A Column_B Akash.Bansal Deactivate_User Akash.Bansal Deactivate_Int_User ``` I want the output as : ``` Akash.Bansal | Deactivate_User |Deactivate_Int_User |Delete_User |Delete_Inter_User| ``` I am able to do one column as row . Can any one help to get above out put
I'm not sure what you want to do with this data. Are you looking for a single string, or are you looking for the data from Column\_B to be put in columns for each name (Column\_A) ? If so, you could use a PIVOT statement for this (if Column\_B options are finite) ``` declare @Example table ( Column_A nvarchar(20)...
You can do this by using `STUFF()` function. Try something like this, ``` CREATE TABLE TestUsr(Column_A VARCHAR(50), Column_B VARCHAR(50)) INSERT INTO TestUsr(Column_A, Column_B) VALUES ('Akash.Bansal', 'Deactivate_User'), ('Akash.Bansal', 'Deactivate_Int_User') SELECT Column_B FROM ( SELECT ROW_NUMBER() OVER(PA...
convert the column data to row data
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I'm attempting to create a short script which will take all of the fields from Table1 and insert them into Table2. The basic fields (col1, col2, col3, etc.) I have got covered by something like this: ``` INSERT INTO Table1 (col1, col2, col3, col4, col5, col6, col7) SELECT col1, col2, col3, col4, col5, SYS...
If the invalid values in your columns are always zeros, as you said in a comment, then you can use a fixed value - either a dummy date, or perhaps more reasonably leave the new column null - with a case statement: ``` SELECT ...., CASE WHEN TRIM('0' FROM col6) IS NULL OR TRIM('0' FROM col7) IS NULL OR TRIM('...
I can't say for sure that this is what you are running into, but when I run `SELECT TO_CHAR(1,'00') FROM dual;` the output has an extra space in front of the expected `01`. I would wrap the call to `TO_CHAR()` in a call to `TRIM()` to remove any such spaces. `SELECT TRIM(TO_CHAR(1,'00') FROM dual;` I also noticed t...
Combining multiple VARCHAR fields as 1 DATE when inserting from one table to another in Oracle?
[ "", "sql", "oracle", "sql-insert", "toad", "oracle12c", "" ]
That's my first day in SQL using PostgreSQL 9.4 and I'm lost with some things. I think that I'm close but not enough: Table definition: ``` CREATE TABLE DOCTOR ( Doc_Number INTEGER, Name VARCHAR(50) NOT NULL, Specialty VARCHAR(50) NOT NULL, Address VARCHAR(50) NOT NULL, City VARCHAR(30) NO...
I finally found the solution, this is quite similar to your solutions, I post here to help another people with similar problems ``` SELECT City, Name FROM DOCTOR d, VISIT v WHERE d.Specialty = 'family and comunity' AND not exists(SELECT * FROM visit v WHERE v.doc_number = d.doc_number AN...
``` SELECT d.name, d.city FROM doctor d LEFT JOIN visit v ON v.doc_number = d.doc_number AND v.visit_date BETWEEN '2012-01-01' AND '2013-12-31' WHERE d.specialty = 'family and community' -- or 'family and comunity'? AND v.doc_number IS NULL ORDER BY d.name; ``` * As commented you need ...
SELECT rows from a table that don't have related entries in a second table
[ "", "sql", "postgresql", "join", "left-join", "" ]
How can I join multiple tables together using MySQL? I have 3 separate tables. **Projects** ``` ID Project Name 1 Big Project #1 ``` **Projects Contract Managers** ``` ID Project Id Contract Manager Id 1 1 11 ``` **Contract Managers** ``` ID Name 11 John Smith 26 Bill Smith `...
Just two `INNER JOIN`s seems to be enough : ``` SELECT * FROM `Projects Contract Managers` pcm JOIN `Contract Managers` cm ON pcm.`Contract Manager Id` = cm.`ID` JOIN `Projects` p ON pcm.`Project Id` = p.`ID` ```
Another possiblity from the first suggested I always feel reads better. I think the engine would optimize to the same execution plan. You would want to confirm with EXPLAIN if the tables are large and you are worried about performance. ``` SELECT * FROM `Projects Contract Managers` a, `Contract Managers` b, ...
Multiple joins in MySQL
[ "", "mysql", "sql", "join", "" ]
I'm trying to select value from second table which ID is in my first table. I've tried this: ``` select FIRST_NAME, LAST_NAME, c.name status from STUDENTS left join PAYER_STATUS c on Status = c.ID where status like N'%'||'active'||'%';! ``` but it displays nothing. Here's just empty ev...
use your column name in where clause. coz you have `status` column present in table. so it will check the passed value with that column instead of c.name ``` select s.FIRST_NAME, s.LAST_NAME, c.name as status from STUDENTS s left join PAYER_STATUS c on s.Status = c.ID where c.name like N'%'||'active'||'%';! ```
You can't use column aliases in `WHERE`/`ON`, Also, when `LEFT JOIN` move `WHERE` clause conditions for outer table to `ON` clause, else it will be a regular `INNER JOIN`. ``` select FIRST_NAME, LAST_NAME, c.name status from STUDENTS s left join PAYER_STATUS c on s.somecolumn = c.ID and c.n...
select value from second table which ID is in my first table
[ "", "sql", "oracle", "plsql", "" ]
So I have a table with 7 items. Lets call them: Car, Boat, House, Bike, Wheels, Sink, Bed. We can simply call the table Table Each with the following assigned numbers: ``` (ID) (Item) (#) (parent_id) 1234 - Car - 1 - null 0000 - Boat - 2 - null 2222 - House - 4 - null 6545 - Bike - 5 - null 6547 ...
You should better keep `parent_id` but not the parent name. Here is quick solution to order your table <http://sqlfiddle.com/#!9/2a1fb/3> ``` SELECT * FROM table1 ORDER BY CASE WHEN parent_id IS NULL THEN CAST(ID AS CHAR) ELSE CONCAT(CAST(parent_id AS CHAR),'-', CAST(ID AS CHAR)) END ``` **EDIT 1** Variant #2...
Something like that should work. I assumed the following field id, (#) = order\_num, and parent\_id: ``` SELECT * FROM table as t ORDER BY CASE WHEN parent_id IS NOT NULL THEN (SELECT id FROM table WHERE id = t.parent_id LIMIT 1) ELSE id END, CASE WHEN parent_id IS NULL THEN -1 ELS...
MySQL Order By Fields & Parents
[ "", "mysql", "sql", "" ]
I have a table that has a the following columns: ``` ID(primary key), USER, ACTION TIME LOCATION ``` I am trying to *remove duplicate entries* using the columns: `USER, ACTION, TIME, LOCATION` together. I wrote the following query : ``` DELETE FROM test.testlogins WHERE id IN (SELECT * FROM (SELECT ...
``` DELETE t1.* FROM testlogins t1 INNER JOIN testlogins t2 ON t1.user=t2.user AND t1.action=t2.action AND t1.time=t2.time AND t2.location=t2.location AND t1.id>t2.id ``` you can use `t1.id>t2.id` if you want to keep the row with the minimum ID or `t1.id<t2.id` if you want to keep the one with ...
Easiest solution is adding a Unique index to the table using `ALTER IGNORE`. This will avoid the issue in future, if the table size is not huge. ``` ALTER IGNORE TABLE testlogins ADD UNIQUE KEY (USER, ACTION, TIME, LOCATION) ``` **OR** Create a new table in some other database with new unique index and load all the ...
MySQL removing Duplicate Rows with Primary Key
[ "", "mysql", "sql", "primary-key", "" ]
``` Animal Count Color ------ ----- ----- Dog 2 brown Cat 4 black Result Animal Color ------ Dog brown Dog brown Cat black Cat black Cat black Cat black ```
You can achieve It with `Common Table Expression` in following: ``` CREATE TABLE #Test ( Animal NVARCHAR(20), CountAnimals INT, Color NVARCHAR(20) ) INSERT INTO #Test VALUES ('Dog', 2, 'brown'), ('Cat', 4, 'black'); WITH CTE AS ( SELECT Animal,CountAnimals,Color FROM #Test UNION ALL SELECT A...
You need to introduce an artificial table (or view) the\_row\_holder\_table with row count>=max count in the initial table. Then just ``` select gr.Animal, gr.Color from grouped gr join the_row_holder_table on gr.count<the_row_holder_table.row ``` UPDATE: Suppose the the\_row\_holder\_table has just one column `row`...
How to reverse a GROUP BY like table?
[ "", "sql", "sql-server-2008", "" ]
``` Select * from TableName where columnA = value1 AND columnB = value2 and column3 IN (list of ids); ``` **How will the above query work in either of the DBs.** How is it different from the following loop query:- ``` for x in list_of_ids: Select * from TableName where columnA = value1 AND columnB = val...
The second example is simply a loop where select will be done X number of times. The execution first example: 1. If number of values are small IN will be transformed to ORed conditions. 2. If number of values are huge some db engines will optimize it and create a spool with all the values and do a join with your table...
The later example is not a query. You have a loop (probably Python) that is executing a specific query (with a specific value for column3) each time. Is this a fictitious example or taken from a specific DB ?
How does IN query work in SQL
[ "", "sql", "nosql", "" ]
I am trying to combine the multiple rows into a single row , i was able to get the half of it i tried many ways get the remaining half , below is the sql i wrote. any help will be appreciated. ``` DROP TABLE #TEST_DEPT_NAME CREATE TABLE #TEST_DEPT_NAME ([ID] [varchar](255) NULL,[CSN_ID] [varchar](50) NULL,[NOTE_ID] ...
you can do it by using `left` and `stuff` functions with `group by`: ``` select t.ID ,t.CSN_ID,t.NOTE_ID,t.DEPARTMENT_NAME, STUFF(( select ' ' + t1.NOTE_TEXT from #TEST_DEPT_NAME t1 where t.ID =t1.ID and t.CSN_ID=t1.CSN_ID and t.NOTE_ID=t1.NOTE_ID and t.DEPARTMENT_NAME=t1....
I think this query is the desired one: ``` SELECT distinct ID,[CSN_ID],[NOTE_ID],[DEPARTMENT_NAME],[NOTE_TEXT] = ( select ' '+ case when [NOTE_TEXT]= '' then null else [NOTE_TEXT]end from #TEST_DEPT_NAME P1 WHERE P1.[ID] = P2.[ID] AND P1.[CSN_ID] =P2.[CSN_ID] AND P1.NOTE_ID = P2.NOTE_ID AND P1.DEPARTMENT_NAME = ...
Combining the multiple records(rows) into single record(row)
[ "", "sql", "sql-server", "t-sql", "ssms", "" ]
I have a couple of tables which have keywords as column names. I am not able to write a subquery using them. Even if I use non-existing column names, the query works. For example ``` CREATE TABLE tgt("view" int); CREATE TABLE src(id int); select * from tgt where view in (select view from src); view ------ (0 rows...
> when I use a non-existing column name in a subquery, it works. Well, but not the way you think it works. It will resolve to the column in some other part of the query (here the other table). ``` select * from tgt where view in (select view from src); ``` is the same as ``` select * from tgt where view in (select...
Another alternative is to use an inner join instead of the subquery. The ambiguity in column names is more obvious here, and you can use aliasing to remove the ambiguity, e.g.: ``` select DISTINCT t.* from tgt t inner join src s on t.view = s.view; ```
Columns with keywords as names in PostgreSQL
[ "", "sql", "postgresql", "keyword", "" ]
I have a very basic statement, e.g.: ``` SELECT pet, animal_type, number_of_legs FROM table ``` However, where `table` currently is, I want to insert some fake data, along the lines of: ``` rufus cat 3 franklin turtle 1 norm dog 5 ``` Is it possible to "generate" these fake records, associ...
``` SELECT pet, animal_type, number_of_legs FROM table union select 'rufus', 'cat', 3 union select 'franklin', 'turtle', 1 union select 'norm', 'dog', 5 ``` This gives you the content of `table` plus the 3 records you want, avoiding duplicates, if duplicates are OK, then replace `union` with `union all` ...
I'm not entirely sure what you're trying to do, but MySQL is perfectly capable of selecting "mock" data and printing it in a table: ``` SELECT "Rufus" AS "Name", "Cat" as "Animal", "3" as "Number of Legs" UNION SELECT "Franklin", "Turtle", "1" UNION SELECT "Norm", "Dog", "5"; ``` Which would result in: ``` +----...
Generating "Fake" Records Within A Query
[ "", "mysql", "sql", "" ]
I simply want to prevent users from running UPDATE statement without WHERE clause. I provided my PLSQL below ``` create or replace PROCEDURE secure_update(update_query IN varchar2) IS msg varchar2(30000); flag char(1); qry varchar2(30000); BEGIN IF upper(update_query) LIKE 'UPDATE%SET%WHERE%=%' THEN flag ...
This works, please see the changes, dont use the into clause in execute immediate ``` create or replace PROCEDURE secure_update(update_query IN varchar2) IS msg varchar2(30000); flag char(1); qry varchar2(30000); BEGIN IF upper(update_query) LIKE 'UPDATE%SET%WHERE%=%' THEN flag := '1'; dbms_output.put...
SQL Developer (and SQL\*Plus, but possibly not other clients!) needs the `exec` command to be on a single line. You didn't show the earlier errors you would have got from that invocation: ``` EXEC secure_update Error report - ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'SECURE...
Invalid SQL type: sqlKind = UNINITIALIZED - PLSQL Error
[ "", "sql", "oracle", "plsql", "" ]
Given the following table, ``` PersonID Year ---------- ---------- 1 1991 1 1992 1 1993 1 1993 2 1990 2 1991 3 1991 3 1992 3 1994 ``` Is there a way with a SQL select query to get the PersonID where it has at least 3 rows with conse...
I think something like the following should work: ``` SELECT personID FROM ( SELECT CASE WHEN year - min(year) OVER (PARTITION BY PersonID ORDER BY YEAR ASC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) = 2 THEN 'x' END as ConsecutiveFlag, PersonID FROM (SELECT pers...
Try: ``` select a.PersonID from Table a left join Table b on a.Personid = b.Personid and a.year = b.year + 1 left join Table c on a.Personid = c.Personid and b.year = c.year + 1 where b.year is not null and c.year is not null and a.year <= 1995 and c.year >= 1990 ```
Determine if field values meet minimum consecutive years within a year range
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I need some hints.. I got a table which looks like that: ``` id fruit delicious 1 apple 1 2 apple 0 3 apple 1 4 cherry 1 5 cherry 1 6 cherry 1 7 banana 0 8 banana 0 9 banana 0 ``` For this table I want to create a statement which will only return the fruits which are completely delici...
Group by the `fruit` and take only those having zero records with `delicious = 0` ``` SELECT fruit FROM fruits GROUP BY fruit HAVING sum(case when delicious = 0 then 1 else 0 end) = 0 ```
Just look for those that have a min delicious value of 1 ``` SELECT Id, Fruit FROM fruits GROUP BY Id, Fruit HAVING min(delicious) = 1 ```
SQL select only rows which have same column value
[ "", "mysql", "sql", "db2", "" ]
I have a table that looks like this: ``` RN ID1 ID2 Name Source 1 W76544 945297 1_W_HO HO 2 W76544 945297 1_W_INT Int 1 W76547 945299 3_W_HO HO 2 W76547 945678 3_W_INT Int 1 W76561 NULL Dev_U_W AD 2 W76561 207283 Dev_W_HO ...
Try with this: ``` Create table t(id int, c char(1)) Insert into t values (1, 'a'), (1, 'a'), (2, 'b'), (2, null), (3, null), (3, null), (4, 'c'), (4, 'd') ;with cte as( select id, count(*) c1, count(c) c2, count(distinct c) c3 from t group by id) select t.id, t.c, ca.m from t Cross apply(select case when c2 = 0 and...
Can you do something like this: ``` SELECT m.RN, m.ID1, m.ID2, CASE WHEN NOT EXISTS (SELECT 1 FROM MyTable WHERE ID1 = m.ID1 AND ID2 IS NOT NULL) THEN 'Empty' ELSE CASE WHEN COUNT(*) OVER(PARTITION BY m.ID1, m.ID2) > 1 THEN 'Yes' ELSE 'No' END END "Matched", m.N...
SQL: Compare Columns for Exact Match of sets
[ "", "sql", "sql-server", "t-sql", "analytics", "ssms", "" ]
This query gives me the desired result but i can't run this query every time.The 2 loops is costing me.So i need to implement something like view.But the logic has temp tables involved which isn't allowed in views as well.so, is there any other way to store this result or change the query so that it will cost me less. ...
You can generate the number of rows and columns and then CROSS APPLY with those, like below. I've left out your SellerID condition. ``` ;WITH Cols AS ( SELECT StructureID, SiteID, CAST(Cols / 8.5 AS INT) AS Col FROM Structure UNION ALL SELECT s.StructureID, s.SiteID, Col - 1 FROM Structure s ...
Do this with a set-based operation. I think you just want `insert . . . select`: ``` INSERT INTO @Temp (SiteID, StructureID, row, col) SELECT StructureID, SiteID, Cols / 8.5 AS Cols, Rows / 11 AS Rows FROM Structure WHERE SellerID = 658; ``` You should avoid cursors, unless you really need them for some r...
How to tune the following query?
[ "", "sql", "performance", "sql-server-2008", "sql-tuning", "query-tuning", "" ]
I have table with such structure ``` CREATE TABLE UsersHistory ( Id INT IDENTITY, UserID INT, StatusId INT, CreateTime DATETIME, ChangedTime DATETIME ) INSERT INTO UsersHistory(UserID, StatusId, CreateTime, ChangedTime) SELECT 1,1,'20150414','20150414' UNION ALL SELECT 1,2,'20150...
You can use `ROW_NUMBER()` with `PARTITION` to achieve this. Something like this ``` ;WITH CTE as ( SELECT UserID, StatusId, CreateTime, ChangedTime,ROW_NUMBER()OVER(PARTITION BY UserID ORDER BY ChangedTime DESC) r FROM UsersHistory WHERE ChangedTime < '20150416' ) SELECT UserID, StatusId FROM CTE WHERE ...
In SQL Server 2012+, you can use `first_value()`: ``` SELECT uh.UserID, FIRST_VALUE(uh.StatusId) OVER (PARTITION BY uh.UserId ORDER BY ChangedTIme DESC) MAX(uh.ChangedTime) AS Dt FROM UsersHistory AS uh WHERE uh.ChangedTime < '20150416'; ```
Simplify SQL select statement
[ "", "sql", "t-sql", "" ]
I have looked through many of the questions already asked on here but have not yet found one that I can adapt to my own situation. I currently have a table filled with values that are used for dropdowns on various webpages I have assembled. I am attempting to add support for SMS messaging. To do this I have added a co...
This should do it: ``` SELECT FoodType, Ingredients, ROW_NUMBER() OVER (PARTITION BY FoodType ORDER BY FoodType) AS smsID FROM dbo.Dropdowns ```
The CTE update method is much faster than subqueries or self-joins [**SQL Fiddle Demo**](http://sqlfiddle.com/#!6/347fc/2) ``` ;WITH t(old,new) AS ( SELECT smsID ,REPLACE(STR(ROW_NUMBER() OVER(PARTITION BY FoodType ORDER BY ingredients)-1,3),' ','0') FROM MyTable ) UPDATE t SET old = new ```
Increment integer MSSQL
[ "", "sql", "sql-server", "" ]
How to update a row to replace percent character. ``` UPDATE MPOLITICAS SET NOM_POLITICA = REPLACE(NOM_POLITICA, '%' , 'PERCENT '); ``` The row content is `NG DEBT 100% - 2014` but should be `NG DEBT 100 PERCENT - 2014`
Replace function should work fine for this: ``` UPDATE MPOLITICAS SET NOM_POLITICA = REPLACE(NOM_POLITICA, '%' , ' PERCENT'); ``` <http://sqlfiddle.com/#!4/cc2c4/1>
Assuming your locale (NLS settings) have ASCII 37 as the % character: ``` UPDATE MPOLITICAS SET NOM_POLITICA = REPLACE(NOM_POLITICA, CHR(37) , ' '); ```
How to replace percent (%) character
[ "", "sql", "oracle", "replace", "sql-update", "" ]
Let's say you have a model for Items with an attribute of Votes. Here might be some sample data: ``` Item, Votes ----------- Red 4 Blue 5 Black 5 Green 4 Cyan 5 Yellow 4 Orange 4 ``` I want a scope that first sorts it by Votes: ``` Item, Votes ----------- Orange 4 Green 4 Yellow 4 Red 4 Bl...
In the item model I made this method: ``` def rand_value self.votes + Random.rand end ``` And then in the controller I am using this query: ``` @items = @experiment.items.sort_by { |item| [item.rand_value] } ``` This seems to be working like I wanted. The first items on the list are always the ones with the least...
Depending on exactly what you want, you have two options. If you want the first two in the complete result (highlighted below), your second solution works. If however, you want the first row of each group, you'll need to modify your query somewhat (as shown below:) --- **First rows of complete result:** ``` scope :o...
Sort database query by column and then randomly
[ "", "sql", "ruby-on-rails", "postgresql", "" ]
I am working with a database with a structure similar to the illustration below (except with more columns). Basically, each person has a unique person\_id and alt\_id. However, the only thing connecting table A to table C is table B, and table B has one to many rows for each person/alt\_id. I need to get rows with a p...
Join to `(select distinct * from b) b` rather than just the base table `b`. ``` SELECT a.person_id, a.color, b.alt_id, c.shape FROM a INNER JOIN (select distinct * from b) b ON a.person_id = b.person_id INNER JOIN c ON b.alt_id = c.alt_id ```
You could use aggregation along with a common table expression (or subquery, but a CTE might be neater): ``` WITH ab AS ( SELECT a.person_id, a.color, MAX(b.alt_id) AS alt_id FROM a INNER JOIN b ON a.person_id = b.person_id GROUP BY a.person_id, a.color ) SELECT ab.person_id, ab.color, ab.alt_id...
Three table join where middle table has duplicate foreign keys
[ "", "sql", "oracle", "join", "" ]
I have two tables. * Purchase Orders(PURCHASE\_ORDER) * Purchase Order Lines(PURC\_ORDER\_LINE) I need the price and currency for a specific part and I also need the row returned to be the latest record in the database. I figure since I want the latest record I need to select the max(date) the only issue is that sin...
Maybe something like this: (see also <https://msdn.microsoft.com/ru-ru/library/ms189463.aspx>) ``` SELECT TOP(1) PURC_ORDER_LINE.LAST_RECEIVED_DATE, UNIT_PRICE, PURCHASE_ORDER.CURRENCY_ID FROM PURC_ORDER_LINE LEFT JOIN PURCHASE_ORDER ON PURC_ORDER_LINE.PURC_ORDER_ID = PURCHASE_ORDER.ID WHERE PAR...
Why use GROUP BY when you only need TOP 1 and ORDER BY? ``` SELECT TOP 1 LAST_RECEIVED_DATE, UNIT_PRICE, CURRENCY_ID FROM PURC_ORDER_LINE LEFT JOIN PURCHASE_ORDER ON(PURC_ORDER_LINE.PURC_ORDER_ID = PURCHASE_ORDER.ID) WHERE PART_ID = 'some part' ORDER BY LAST_RECEIVED_DATE DESC ```
SQL Select line with most recent date
[ "", "sql", "sql-server-2008", "" ]
I have a table like so ``` Fld1 Fld2 Fld3 ------------ 0 1234 ABC 0 1235 DEF 1 1236 GHI 2 1236 JKL 3 1236 MNO 4 1237 PQR 5 1237 STU 6 1237 VWX ``` Note that neither column is unique. There may be many rows with Fld1 = 0, but for all other values Fld1 will be unique a...
An alternative to `GROUP BY` would be to use a windowing function like [`row_number()`](https://msdn.microsoft.com/en-us/library/ms186734.aspx) to get the result. This function creates a unique number by partitioning your data by `Fld2` and ordering it by `Fld1 desc`: ``` select Fld1, Fld2, Fld3 from ( select Fld1, ...
Use `group by`: ``` select max(fld1), fld2 from table t group by fld2; ```
Selecting single row with no unique key
[ "", "sql", "sql-server", "" ]
I am struggling with a SQL function for a report I am writing. The function polls an audit table for the original value of a particular field (SecondarySchoolCode). If it finds a value in the audit table for the current row it should return the value, if there is no value for the current row then the original parameter...
I'm not sure what all of your relationships are, but based on your stated requirements and your current query, you are joining to some tables you don't need. The reason you don't get anything back when the audit doesn't exist is because there are no rows from which to select a `TOP 1`. This should always return at leas...
Biscuits provided the easiest to implement solution: I mean, something like ISNULL(dbo.fn\_AuditOriginalHSAttendingCode(...), 'SecondarySchoolCode') – Biscuits 59 mins ago
Multiple SQL or Case statements in Scalar function
[ "", "sql", "sql-server", "function", "" ]
I have a table of people records like this: ``` Tableid PeopleID DeptID StartMonth StartYear -------------------------------------------- 1 101 1 3 2014 2 101 2 2 2015 3 102 2 5 2015 4 102 5 4 2013 5 ...
Use `row_number()`: ``` select t.* from (select t.*, row_number() over (partition by peopleid order by startyear desc, startmonth desc ) as seqnum from table t ) t where seqnum = 1; ```
You can use `ROW_NUMBER()` with `PARTITION BY`. Something like this. ``` CREATE TABLE People ( Tableid INT, PeopleID INT, DeptID INT, StartMonth INT, StartYear INT ) INSERT INTO People SELECT 1, 101, 1, 3, 2014 UNION ALL SELECT 2, 101, 2, 2, ...
SQL Server Query output
[ "", "sql", "sql-server", "" ]
as you can see I am working in SQL Developer and trying to get some data out of my tables. I'm trying to get out the item with its biggest price, but don't know how to manage it. For price I was trying SELECT MAX(price) FROM price but I get return 95€, when the biggest price is 350€. Can someone help me, that I Wil...
First, change the column type to integer. Right now, I assume, it is VARCHAR or TEXT. As it sorts by the first symbol, of course 9 > 3, that's why you get the weird results. Remove the € from the row's content and move it to another column.
You would seem to be storing the price as a string and not as a number. In MySQL, you can use silent conversion to get what you want: ``` SELECT MAX(price + 0) FROM price; ``` In Oracle, for this example, you can just do: ``` SELECT MAX(to_number(replace(price, '€', ''))) FROM price; ``` although a regular expressi...
How to select item with the biggest price?
[ "", "mysql", "sql", "oracle", "" ]
How can I accomplish something like this in a query. If I have the total amount of 673000 that is passed as a parameter in my stored proc then, I need to do this: ``` Declare @TotalAmount money @TotalAmount = 673000 Col1 Col2 Col3 Test1 45 672955 --(I want to subtract 673000 from Col2 data) ...
Assuming you want to `ORDER` based on `Col1`, in SQL Server 2012 and above you can do something like this ``` DECLARE @TotalAmount money SET @TotalAmount = 673000 ;WITH CTE as ( SELECT 'Test1' col1 ,45 col2 UNION ALL SELECT 'Test2' ,30 UNION ALL SELECT 'Test3' ,100 ) SELECT col1,col2,@TotalAmount - SUM(co...
``` DECLARE @amount decimal DECLARE db_cursor CURSOR FOR SELECT amount FROM TABLE OPEN db_cursor FETCH NEXT FROM db_cursor INTO @amount WHILE @@FETCH_STATUS = 0 BEGIN @TotalAmount = @TotalAmount - @amount FETCH NEXT FROM db_cursor INTO @amount END CLOSE db_cursor DEALLOCATE db_cursor ```
subtracting the current row remaining balance with previous row balance
[ "", "sql", "sql-server", "" ]
I have a MySQL query with this line ``` ORDER BY -order_line_groups.sequence DESC, order_line_groups.id; ``` I'm trying to find out what the hyphen is for just after the order by. I have tried executing with and without it but it does not seem to make a difference. I have also looked at it with explain and cant find ...
The answer is in the question: > I did find this: <https://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html> where the hyphen is listed under *"You use ORDER BY with an **expression**..."* The keyword here is **"expression"**. You can use expressions in the `ORDER BY` clause. ``` ORDER BY -order_line_group...
you are negating the value of column 'sequence' and using it in order by .. ``` order by -(number) ``` ordering by negation of a number.
hyphen in MySQL order by clause
[ "", "mysql", "sql", "" ]
I am new to Sql server, I tried datediff several times but failed. All I need is the exact or precise number of minutes including fraction between two dates. E.g if the gap between two datetime fields is 40 seconds than it gives me 0.67 minutes and not 1 minute. Please help.
Take the difference in seconds and divide by 60.0: ``` select datediff(second, date1, date2) / 60.0 as diff_in_minutes ``` This should be close enough for most work. If you really want, you could use milliseconds instead of seconds.
``` select datediff(millisecond, date1, date2) / 60000.0 as diff_in_minutes ```
How can I find exact number of minutes without rounding between two dates in sql server
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "" ]
I want to get the unique values from two small lists and use the result to select those from a big list. However, only the first result is returned. What am I doing wrong? Query: ``` SELECT DISTINCT b.keys, b.names FROM biglist b WHERE b.keys = (SELECT keys FROM partial_list_1 UNION SELECT keys FROM partial_list_2) `...
It is generally much more efficient to represent this as two different operations using `or`: ``` SELECT DISTINCT b.keys, b.names FROM biglist b WHERE b.keys IN (SELECT keys FROM partial_list_1) OR b.keys IN (SELECT keys FROM partial_list_2); ``` These can take advantage of indexes on `partial_list_1(keys)` and...
You should use `IN`: ``` SELECT DISTINCT b.keys, b.names FROM biglist b WHERE b.keys IN (SELECT keys FROM partial_list_1 UNION SELECT keys FROM partial_list_2) ```
SQL select from union only returns the first match
[ "", "sql", "select", "union", "" ]
I have this data. ![enter image description here](https://i.stack.imgur.com/SDrJK.png) this is my query ``` SELECT transaction_date FROM tenant1.txn_transaction_record where '2015-04-14' ``` The said query renders empty result. Is it possible to query timestamp field using only date?
When you do: ``` transaction_date = '2015-04-14' ``` PG will convert string '2015-04-14' to timestamp '2015-04-14 00:00:00' value. If you do: ``` transaction_date::date = '2015-04-14' ``` PG will convert both values to date (wich is only date part, without time part), and it'll work. **BUT... BE CAREFUL WHEN CAST...
No, If you do like `transaction_date = '2015-04-14'` It will automatically search for `transaction_date = '2015-04-14T00:00:00'` So you wont yield any result. Therefore if you want to search the date try `transaction_date::date = '2015-04-14'` So the final query is, ``` SELECT transaction_date FROM tenant1.txn_tr...
Postgresql querying timestamp data with date only
[ "", "sql", "postgresql", "" ]
I'm struggling a little bit with syntax. I'm trying to have the following line of code, with the upper boundary determined by a hard value and a sub-query or two sub-queries, picking the minimum value of the result. ``` AND ELIGTY_MO_YYYYMM BETWEEN '201407' AND '201412' ``` with the intended change being: ``` AND E...
A couple of things... 1. When comparing two values, use `LEAST` and `GREATEST`. `MIN` and `MAX` are for aggregating only. 2. When using a subquery as a value in a column or expression, enclose the subquery in parentheses. ``` AND ELIGTY_MO_YYYYMM BETWEEN '201407' AND LEAST('201412, (SELECT MAX(whatever) FROM...
Perhaps you are looking to use `least` instead. Very generic example: ``` select * from yourtable where someval between 0 and least((select min(someval) from yourtable), (select max(someval) from yourtable)) ``` * [Condensed Fiddle](http://sqlfiddle.com/#!4/76c62/5)
Min Value Oracle with results of subqueries
[ "", "sql", "oracle", "" ]
I have an app that has the built in initial Select option and only allows me to enter from the Where section. I have rows with duplicate values. I'm trying to get the list of just one record for each distinct value but am unsure how to get the statement to work. I've found one that almost does the trick but it doesn't ...
There are two keywords you can use to get non-duplicated data, either `DISTINCT` or `GROUP BY`. In this case, I would use a `GROUP BY`, but you should read up on both. This query groups all of the records by CallIndex and takes the `MAX` value for each of the other columns and should give you the results you want: ``...
If the constraint is that we can only add to the WHERE clause, I don't think it's possible, due to there being 2 absolutely identical rows: ``` 4/15/2015 | Jane | 5555051005 | 00000.0050 4/15/2015 | Jane | 5555051005 | 00000.0050 ``` Is it possible that you can add HAVING or GROUP BY to the WHERE? or poss...
SQL Where Query to Return Distinct Values
[ "", "sql", "distinct", "where-clause", "" ]
I am importing working with data imported from excel files. There is a column with a string that can contain multiple numbers. I am trying to extract the largest number in the string or a 0 if there is no string. The strings are in formats similar to: "100% post-consumer recycled paper, 50% post-consumer recycled cover...
Here's a scalar function that will take a string as an input and return the largest whole number it finds (up to a maximum of 3 digits, but from your question I've assumed you're dealing with percentages. If you need more digits, repeat the IF statements ad infinitum). Paste this into SSMS and run it to create the fun...
1. Pull the data into SQL as-is 2. Write a query to get a distinct list of options in that column 3. Add a new column to store the desired value 4. Write an update statement to populate the new column As far as determining the largest size, I think you need to look at your data set first, but the update could be as si...
Extract largest number from a string in T-SQL
[ "", "sql", "sql-server", "t-sql", "string-matching", "extract", "" ]
I have the following entries in the table: ``` SQL> select TO_CHAR(startdate, 'DAY') from ragreement; TO_CHAR(STARTDATE,'DAY') ------------------------------------ WEDNESDAY THURSDAY SUNDAY FRIDAY MONDAY SUNDAY MONDAY MONDAY THURSDAY SATURDAY TUESDAY SUNDAY FRIDAY WEDNESDAY FRIDAY SUNDAY THURSDAY MONDAY THURSDAY WEDN...
Try: ``` SELECT COUNT(*) FROM ragreement WHERE TRIM(TO_CHAR(startdate, 'DAY')) = 'TUESDAY' ``` I think there is space padding space padding. Don't need `UPPER` since the formatting model used already is forcing upper case. Please see [Number Format Models](http://docs.oracle.com/cd/B28359_01/server.111/b28286/sq...
For completeness sake, here is an alternative: ``` SELECT t.day, COUNT(*) FROM (SELECT TRIM(TO_CHAR(startdate, 'DAY')) day FROM ragreement) t GROUP BY t.day ``` Naturally since no string comparison is involved in this solution, this could (and should) be simplified: ``` SELECT TO_CHAR(startdate, 'DAY'), COUNT(*)...
Oracle SQL String Compare
[ "", "sql", "oracle", "select", "count", "" ]
I am trying to get the percent and it just shows up as zero. I want to show two decimal places such as 0.65 Here is a piece of the query I am selecting: ``` select count(numbers)/count(othernumbers) decimal(3,2) as"rate" ``` if I use this it shows up as 0 and gets rid of the rest ``` select count(numbers)/count(othe...
``` SELECT FORMAT(this / that, 2) as rate ``` Meanwhile, I question whether `COUNT(numbers)` is what you want. That counts how many rows have a non-NULL value in the column `numbers`. Also, fraction is usually more like `x / (x+y)` -- meaning the fraction of the total (x+y) that is x. A "percentage" needs `100*` som...
need to convert both of your "count(numbers)" and "count(othernumbers)" to decimal also. ``` select convert(decimal(5,2), count(numbers)) / convert(decimal(5,2), count(othernumbers)) as"rate" ``` Here's an example that works in SSMS (Sql Server): ``` select Convert(decimal(3,2), convert(deci...
how to show decimals in sql instead of 0
[ "", "mysql", "sql", "decimal", "" ]
let's say this is the result of my Select query : ``` ID Name Status Edit Date 1 n1 closed edt1 01/01/2005 1 n1 closed edt2 15/01/2005 1 n1 closed edt3 20/01/2005 ``` What I'm trying to do, is to get the diff between the date of edit1 and the date of edit...
You can use the `LEAD()` analytic function: ``` SELECT id, name, status, edit, date, LEAD(date) OVER ( PARTITION BY id ORDER BY date ) - date AS edit_diff FROM mytable; ``` If you want to put a certain number of edits into their own columns, you could then PIVOT the date returned from the above query; if the # of e...
I would add an incrementing id column like this: <http://www.orafaq.com/wiki/AutoNumber_and_Identity_columns> and then write your query like this: ``` select x.id, x.name, x.status, y.edit, y.date, y.date - z.date from (table1 x left join table2 y on x.id = y.id left join table2 z on y.newid = z.newid - 1) where x.id ...
difference between two fields from different rows
[ "", "sql", "oracle", "" ]
I have a table with column data in below format(Row# just to indicate row number). ``` Row#1 :test.doc#delimiter#1234,test1.doc#delimiter#1235,test2.doc#delimiter#1236<br> Row#2 :fil1.txt#delimiter#1456,fil1.txt#delimiter#1457 ``` I want to split the string using comma(,) as delimiter, list all in one single column a...
``` WITH data AS ( SELECT 'test.doc#delimiter#1234,test1.doc#delimiter#1235,test2.doc#delimiter#1236' AS "value" FROM DUAL UNION ALL SELECT 'fil1.txt#delimiter#1456,fil1.txt#delimiter#1457' AS "value" FROM DUAL ) SELECT REGEXP_SUBSTR( data."value", '[^,]+', 1, levels.COLUMN_VALUE ) FROM data, TABLE( ...
An easy way would be to, for each row, split the string into multiple rows and insert it to the destination table. There are multiple ways to split a single string into multiple rows on this site. A simple search should give you some answers. Assuming your table is called origtable, the column that has those strings i...
Split string oracle into a single column and insert into a table
[ "", "sql", "oracle", "oracle10g", "oracle-sqldeveloper", "" ]
I have a two tables with alarming information from multiple different computers. I would like to return a list of specific alarms for a specific computer, and also include the previous alarm for that same computer. Table 1: Computer Info ``` ComputerInfoId| ComputerName| [Desc] 1 | Desktop1 | Front...
Your sample output data doesn't match the input data,and I can't tell if you want two previous errors for each matching error, or one previous error for each of 2 errors in the sample data. I think that this query will work on a larger dataset where the previous alarm for a machine might not be the previous AlarmDataID...
I think this work for you : ``` Select ComputerInfo.ComputerInfoId ,ComputerInfo.ComputerName ,AlarmData.AlarmDataId ,AlarmData.AlarmId ,AlarmData.AlarmDate ,TB.AlarmId As PreAlarmId ,TB.AlarmDate As PreAlarmDate From ComputerInfo inner join AlarmData On AlarmData.ComputerInfoId =ComputerInfo.ComputerInfo...
SQL Server - Find previous record based upon ID and Computer Name
[ "", "sql", "sql-server-2008", "t-sql", "" ]
Given that each GUID is represented by 16 bytes. So at best there are 2^128 possibilities = 3.4028237e+38 possible GUIDs. Will it be possible that it will all be used up?
No. Even if you assume *extremely* high usage of GUIDs in some area, and *extremely* long time scales, the key point about GUIDs is their uniqueness. As soon as you start to get repetitions with any probability that is of practical relevance, people will stop using GUIDs, and therefore won't use up any more of them. Su...
To show you how big 2^128 GUIDs is: 1 GUID = 16 bytes. Therefore 2^128 GUIDS would each need 16 bytes of storage, that is: `2^4 * 2^128 = 2^132 bytes` [This works out to be](https://www.wolframalpha.com/input?i2d=true&i=Power%5B2%2C4%5D*Power%5B2%2C128%5D) `5,444,517,870,735,015,415,413,993,718,908,291,383,296 byte...
Is there any possibility that GUID will all be used up?
[ "", "sql", "math", "guid", "uuid", "" ]
I've got a table with a few columns, and for each row I want the maximum: ``` -- Table: +----+----+----+----+----+ | ID | C1 | C2 | C3 | C4 | +----+----+----+----+----+ | 1 | 1 | 2 | 3 | 4 | | 2 | 11 | 10 | 11 | 9 | | 3 | 3 | 1 | 4 | 1 | | 4 | 0 | 2 | 1 | 0 | | 5 | 2 | 7 | 1 | 8 | +----+----+----...
What about unpivoting the data to get the result? You've said tsql but not what version of SQL Server. In SQL Server 2005+ you can use [`CROSS APPLY`](https://technet.microsoft.com/en-us/library/ms175156%28v=sql.105%29.aspx) to convert the columns into rows, then get the max value for each row: ``` select id, row_max ...
You can use the following query: ``` SELECT id, (SELECT MAX(c) FROM ( SELECT c = C1 UNION ALL SELECT c = C2 UNION ALL SELECT c = C3 UNION ALL SELECT c = C4 ) as x(c)) maxC FROM mytab...
Row-wise maximum in T-SQL
[ "", "sql", "t-sql", "unpivot", "" ]
Given the following table, ``` PersonID Year ---------- ---------- 1 1991 1 1992 1 1993 1 1994 1 1996 1 1997 1 1998 1 1999 1 2000 1 2001 1 2002 1 2003 2 1999 2 2000 ... ... ``` Is ...
Using two CTEs to create row number groupings allows you to group by PersonID and display all personIDs that it applies to: ``` Declare @MinimumConsecutiveYears int=4 ;With YearGroupings as ( Select PersonID ,year ,row_number() over(partition by personid order by year asc) rown From @y...
You can create [islands of years](https://www.simple-talk.com/sql/t-sql-programming/the-sql-of-gaps-and-islands-in-sequences/) in the cte and check your conditions: ``` declare @PersonId int = 1, @cnt int = 4 ;with cte_numbered as ( select PersonID, [Year], row_number() over(...
Determine first year of minimum consecutive year range and count of consecutive years
[ "", "sql", "sql-server", "sql-server-2012", "" ]
What is the usage of `@@` in SQL Server?
[According to MSDN](https://msdn.microsoft.com/en-us/library/ms187786.aspx), the correct name for these is `system functions`. The naming confusion (global variable, system function, global function) stems from different terminology used throughout SQL Server's history. From the [MSDN Transact-SQL Variables article](h...
`@` is for a local variable `@@` is for a global variable or function. There are several standard global variables or functions, e.g.: `@@IDENTITY`, `@@ROWCOUNT`, `@@TRANCOUNT`
What is the usage of '@@' in SQL Server
[ "", "sql", "sql-server", "special-characters", "" ]
I have two tables. One is the `Course` table and the second is the `Teacher` table. I want to get all `Teacher` who does not teach `'Math'`. How can I do this? Course Table ``` course_id course teacher_id marks 1 Physics 1 60 2 Math 1 60 3 Chemestry 1 ...
> I want to get all teacher who does not teachs math. You need to join both the tables on **teacher\_id** and then filter out the rows based on the **course**. ``` SQL> SELECT DISTINCT t.name 2 FROM course c, 3 teacher t 4 WHERE c.teacher_id = t.teacher_id 5 AND c.course <> 'Math'; NAME -------- Te...
``` select * from teacher t where not exists (select 1 from course c where c.teacher_id = t.teacher_id and c.course = 'Math') ``` @LalitKumarB Ben is absolutely right
Give the name of all the teacher who does not teach math
[ "", "mysql", "sql", "oracle", "" ]