Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Say I have a table A with attributes X How do I find the X's with the largest occurrences? (There can be multiple that have the same highest occurrence) i.e. table A ``` X -- 'a' 'b' 'c' 'c' 'b' ``` I would want to get back ``` X -- 'b' 'c' ``` I can't use the keyword ALL in Sqlite so I'm at a loss. I thought of...
This takes care of multiple values having maximum occurence ``` SELECT X FROM yourTable GROUP BY X HAVING COUNT(*) = ( SELECT MAX(Cnt) FROM( SELECT COUNT(*) as Cnt FROM yourTable GROUP BY X ...
Query like ``` SELECT x,COUNT(x) AS cnt FROM a GROUP BY x ORDER BY cnt DESC; ``` and stop processing the result rows when `cnt` changes.
SQLite How to find the most common occurrences of a value
[ "", "sql", "sqlite", "" ]
I have read tips about sql server database on <http://www.sql-server-performance.com/2007/clustered-indexes> In conclusion section author mentioned: "Since you can only create one clustered index per table, take extra time to carefully consider how it will be used." My question is: \**Why only one clustered index pe...
**Clustered Index:** Clustered index defines the way in which data is ordered physically on the disk. And there can only be one way in which you can order the data physically. Hence there can only be one clustered index per table. **Why care about clustered index?** If we put clustered index on the table then the ...
This is simply SQL Server's implementation decision. Theoretically, there are can be any number of clustering indexes. MongoDB and MyISAM have no clustering indexes and store data in a flat file. InnoDB for MySQL has one clustering index, the primary key, which may be hidden if a primary key is not declared. TokuDB for...
Why only one clustered index per table should be created in sql server?
[ "", "sql", "sql-server", "database-administration", "" ]
Apologies, I haven't slept, so just want to clarify something in my head. A team can have many users, but a user can be a member of several teams. Is this a many-to-many relationship? If so, do I need a third table to join them in MySQL?
## Many to many relationships **Many to many relationships** exist and you're right to point that it works somehow differently than many to one / one to many. So it's not **at all** a stupid question. Most of the time, you will need to add extra fields that are characteristics to this relation. Because you'll want to...
Yes. And you almost certainly need to have a third 'relationship' table. The easiest option is to have a relationship table that indicates users on teams. Teams == Rel === Users To query for users on a team, search rel for all usersIds for a teamId and vice versa to check for teams that a user belongs to.
Simple many-to-many relationships
[ "", "mysql", "sql", "" ]
I need to update duplicated records as a invalid, but keep only record. my table structure is as follows: **field Name** ``` id (primary key) phoneNo IsValid ``` Sample data is as follows: ``` id | phoneNo | IsValid -------------------------------------- 1 | 011 | 1 2 ...
remove having clause from your query there is no need of it and try... ``` update phone set IsValid=0 where id in (select id from phone where id not in ( select MAX(id)id from phone group by phoneNo)) and IsValid=1 ```
try this query: ``` UPDATE phone t1 SET IsValid = 0 WHERE t1.ID NOT in (SELECT MAX(t2.ID) FROM phone t2 GROUP BY t2.PHONENO); ```
Update record with count as a condition
[ "", "sql", "sql-server-2005", "" ]
I am constantly selecting columns from a table after trimming them like the following: ``` SELECT TOP 1 RTRIM(LTRIM([UN_DataIN])) FROM [Names] ``` This is returning the name `Fadi` ``` SELECT TOP 1 RTRIM(LTRIM([UN_DataIN])), LEN(RTRIM(LTRIM([UN_DataIN]))) FROM [Names] ``` when I select the length of the trimmed col...
> UN\_DataIN == 0x45062706470631062920292029202920292029202000 So presuming Arabic your string ends with Unicode paragraph separators *U+2029* and then a single whitespace all of which you need to remove; ``` select rtrim(replace(UN_DataIN, nchar(0x2029), '')) + '!' ``` # ماهر!
This is may work for you as my problem too.. ^-^ ``` select rtrim(ltrim(replace(replace(replace(colname,char(9),' '),char(10),' '),char(13),' '))) from yourtable ``` source : <http://www.sqlservercentral.com/Forums/Topic288843-8-1.aspx>
SQL Server - RTRIM(LTRIM(column)) does not work
[ "", "sql", "sql-server", "trim", "" ]
I am using sql 2008 My data set looks like ``` Entity Type1 Type2 Balance 1 A R 100 1 B Z 200 1 C R 300 2 A X 1000 2 B Y 2000 ``` My output should look like ``` Entity A-Type2 A-Balance B-Type2 B-...
Easiest is the MAX idea, but with a CASE statement, e.g.: ``` SELECT Entity, MAX(CASE WHEN Type1 = 'A' THEN Type2 ELSE NULL END) AS AType2, MAX(CASE WHEN Type1 = 'A' THEN Balance ELSE NULL END) AS ABalance, MAX(CASE WHEN Type1 = 'B' THEN Type2 ELSE NULL END) AS BType2, MAX(CASE WHEN Type1 = 'B' THEN Balance ...
You just use conditional aggregation for the pivoting like this: ``` select Entity, max(case when Type1 = 'A' then Type2 end) as A_Type2, max(case when Type1 = 'A' then Balance else 0 end) as A_Balance, max(case when Type1 = 'B' then Type2 end) as B_Type2, max(case when Type1 = 'B' then Bal...
Using Pivot or CTE to horizontalize a query
[ "", "sql", "sql-server-2008", "" ]
I would like to produce results from the alphabet via SQL? Something like this: ``` A B C D E F ``` I have tried: ``` SELECT 'A','B','C' ``` But this just produces the letters across in columns.
``` -- -- tally = 9466 rows in my db, select upper & lower alphas -- ; with cte_tally as ( select row_number() over (order by (select 1)) as n from sys.all_columns ) select char(n) as alpha from cte_tally where (n > 64 and n < 91) or (n > 96 and n < 123); go ``` The sys.all\_columns is a documented table....
Use table `spt_values` and convert values to chars ``` SELECT Char(number+65) FROM master.dbo.spt_values WHERE name IS NULL AND number < 26 ``` EDIT: This table is undocumented. But, it's used by many system storedprocedures and it's extremely unlikely for this table to disappear, since all those procs sh...
create a list of the alphabet via SQL
[ "", "sql", "sql-server", "" ]
I have a table in DB, with following columns: * action\_type * file\_id * time Now, I need to select all actions with particular type and time and use file\_id to delete file. The problem is that I might get several rows from that query, but I only need one, which was last added to DB. Suppose the example records in...
Ok, you can get the latest recored for all distinct file\_id. Normally, this request should work fine in sqlite : ``` SELECT file_id, _id, action_type, Max(time) FROM test GROUP BY file_id; ``` Edit : Ok, your request is more complex : ``` SELECT `_id`, `action_type`, `file_id`, `time` ...
You can use a subquery to get this result: ``` SELECT _id, file_id FROM table t WHERE action_type = x AND t.time = (SELECT Max(time) FROM Table s WHERE s.action_type = t.action_type AND s.file_id = t.file_id) ``` See the following link for how to ...
Select last record from similar in SQLite
[ "", "android", "sql", "sqlite", "" ]
I have a "Has-many-through" table `keyword_sentence` which contains links from the sentences to the keywords. ``` TABLE `keyword_sentence` { `id` int(11) NOT NULL AUTO_INCREMENT, `sentence_id` int(11) NOT NULL, `keyword_id` int(11) NOT NULL, `created` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `sentence_id`...
Try this query ``` SELECT * FROM ( SELECT *, @rowNo := if(@pv = week, @rowNo+1, 1) as rNo, @pv := week FROM ( SELECT keyword_id, COUNT(*), YEARWEEK(FROM_UNIXTIME(created)) AS week FROM keyword_sentence WHERE FROM_UNIXTIME(created) >= CURRENT_DATE - INTERVAL 2 MONTH ...
Have you tried this queryies ?? ``` SELECT DISTINCT(keyword_id) FROM tmp WHERE created BETWEEN '2014-01-01' AND '2014-02-01' LIMIT 0, 20; ``` OR without DISTINCT ``` SELECT keyword_id FROM tmp WHERE created BETWEEN '2014-01-01' AND '2014-02-01' LIMIT 0, 20; ``` Then, if you have five or more per week them appeared,...
MySQL tagging system - top keywords per month
[ "", "mysql", "sql", "subquery", "greatest-n-per-group", "tagging", "" ]
I have a string in the database which is comma separated.Like 'apple,banana,pineapple,grapes' I need to split this string on the basis of comma and iterate through this.Since there is no built in function in sql server, Is there any efficient way in which this objective can be attained.
Try this function ``` CREATE FUNCTION [dbo].[func_Split] ( @DelimitedString varchar(8000), @Delimiter varchar(100) ) RETURNS @tblArray TABLE ( ElementID int IDENTITY(1,1), -- Array index Element varchar(1000) -- Array element contents ) AS BEGIN...
> ... Since there is no built in function in sql server ... That was true at the time you asked this question but SQL Server 2016 introduces [`STRING_SPLIT`](https://msdn.microsoft.com/en-gb/library/mt684588.aspx). So you can just use ``` SELECT value FROM STRING_SPLIT ('apple,banana,pineapple,grapes', ',') ``` T...
Splitting the string in sql server
[ "", "sql", "sql-server", "database", "string", "" ]
I have a mysql table (file\_payments) to keep records of payments contained in a file and looks like this ``` ID FILE START_DATE END_DATE NO_PAYMTS -- ----- ---------- ---------- --------- 1 file1 2013-10-11 2013-10-15 6 2 file2 2013-10-16 2013-10-20 10 ``` Then I have another table (pa...
Query: **[SQLFIDDLEExample](http://sqlfiddle.com/#!2/06499/2)** ``` SELECT t1.ID, t1.FILE, t1.START_DATE, t1.END_DATE, t1.NO_PAYMTS, (SELECT COUNT(*) FROM Table2 t2 WHERE t2.DATE >= t1.START_DATE AND t2.DATE <= t1.END_DATE ) AS ACTUAL_PAYMTS FROM Table1 t1 ``...
Query : ``` SELECT f.id, f.file, f.start_date, f.end_date, f.no_paymnts, COUNT(p.bank) from file_payments f, payments p WHERE p.date BETWEEN f.start_date AND f.end_date GROUP BY f.id; ``` JSFiddle : <http://sqlfiddle.com/#!2/8446f/13>
Select between two dates from other table
[ "", "mysql", "sql", "" ]
In the controller I want to verify if the record with the id in the query `params` exists in the database, but doing something like this `Project.find(params[:id]).present?` errors out if the id doesn't exist. How should I verify presence instead?
You can use `find_by(id: params[:id])` (Rails 4) or `find_by_id(params[:id])` (Rails < 4) which will return `nil` instead of raising ActiveRecord::RecordNotFound. You can also use `Project.exists?(params[:id])`.
In my experience there are two ways. First and preferable, as as stated before - you can use find\_by\_id that returns nil if no object was found. Second - you can use method try(:present?) - but it will return either true or nil (so you'd have to use Project.find(params[:id]).try(:present>).present? - and this seems ...
How can I verify Project.find(12).present? and not get an error if ID 12 doesn't exist?
[ "", "sql", "ruby-on-rails", "ruby", "ruby-on-rails-4", "" ]
I'm trying to compare the result of one query (example: number of rows), between the beginning of the current month and the current date, compared to what happened the previous month. Example: Today is 25/01, so I'd like to know the number of rows created between the 01/01 and 25/01, vs the previous month (same interv...
I've managed to optimise/simplify the query as follows: ``` SELECT TOP(LEFT(DATE(mydate), 7), 2) as month, count(*) as total FROM [mybucket.mytable] WHERE DAY(mydate) BETWEEN 1 and DAY(CURRENT_TIMESTAMP()) AND LEFT(DATE(mydate), 7) >= LEFT(DATE(DATE_ADD(CURRENT_TIMESTAMP(), -1, 'MONTH')), 7); ``` However, I still wou...
Ok lets try again, not that I think I understand what you want. This is somewhat cleaner. Also I included case statement to check if Current and Previous are Equal ``` DECLARE @dayInt INTEGER = 18; SELECT COUNT(CASE WHEN MONTH(GETDATE()) = MONTH(d.Date_Dt) THEN 1 ELSE NULL END) AS 'Curr...
Optimization of BigQuery aggregated data between two dates
[ "", "sql", "optimization", "" ]
I have SQL generated by `JPA`, which in the worst case had 1250 lines. The structure of my query was 20 sub-queries nested inside the `WHERE` statement of a query. This query ran in 0.015 seconds. I tried to optimize my query as I noticed I had reused a lot of joins in the sub-queries (e.g where two sub-queries only ...
With the limited information provided in the question I can only speculate as to exactly why the execution time increases in your specific case, but the long and the short of it is that less code does not equal faster queries. One of the main reasons "simplifying" queries can result in longer execution times is that t...
Maybe those extra lines created much smaller tables *(or selected less data)* than the ones you have atm, hence you could compare tables *(data)* more quickly. However now, as you have reduced the number of smaller tables and presumably increased the size of the bigger ones, the queries has to page through larger table...
Reduced my SQL by 40% but it runs 60 times slower?
[ "", "mysql", "sql", "hibernate", "jpa", "" ]
For example: ``` RouteID StopName 1 stop_1 1 stop_2 1 stop_3 2 stop_1 2 stop_2 3 stop_4 4 stop_5 ``` I want to select the route that it has a stop named 'stop\_1', I expect the results as follows: ``` RouteID StopName 1 sto...
You can use an inner query that selects the routes for that: ``` select r.RouteID, s.StopName from route r inner join stop s on r.StopID = s.StopID where RouteID in (select t1.RouteID from route t1 where exists (select * from stop s2 where t1.StopID = s2.StopID and s2.StopName = 'stop_1')) order by r.RouteID, s.St...
**New Answer for your edit** Again, assuming routes table is named `Routes` and your relation table is named `RouteStops`. ``` SELECT * FROM Routes r JOIN RouteStops rs ON rs.RouteID = r.RouteID WHERE rs.StopName = 'stop_1' ``` **Old Answer:** For the sake of example, I'm going to assume your table name is Routes ...
SQL - select rows that their child rows's column contains specific string
[ "", "sql", "" ]
I am attempting to find duplicates in a single table, where at least one of those duplicates was created in the last day. Here is my query: ``` SELECT DateOfBirth DOB, FirstName FirstName, LastName LastName, COUNT(*) TotalCount FROM TABLE WHERE DateOfBirth IS NOT NULL AND DATEDIFF(d,dateCreated,get...
``` ;WITH x AS ( SELECT FirstName, LastName, DateOfBirth, DateCreated, TotalCount = COUNT(*) OVER ( PARTITION BY FirstName, LastName, DateOfBirth ) FROM dbo.[TABLE] ) SELECT FirstName, LastName, DateOfBirth, DateCreated, TotalCount FROM x WHERE TotalCount > 1 AND DateCreated >= DATEADD(D...
I have revised this as an alternative to Aarons answer, in case you wish to see only the duplicates which are not the original record. ``` ;WITH x AS ( SELECT FirstName, LastName, DateOfBirth, DateCreated, Row_number() OVER ( PARTITION BY FirstName, LastName, DateOfBirth ...
Find Duplicates By Created Date TSQL
[ "", "sql", "sql-server", "" ]
I have table *t* that contains a person's name and the products they have: ``` NAME PRODUCT Adam a Adam b Adam c Ben c Ben d Chris b Dave a Dave b Dave c Dave d Evan a Evan b Fred a ``` And I want a SQL query that returns NAME when the person has Product a or b or both, AND ...
``` SELECT DISTINCT name FROM T WHERE product IN ('a', 'b') AND name NOT IN (SELECT name FROM T WHERE product IN ('c', 'd', 'e', 'f')) ``` Or, if you have all those unwanted c d e f products in another table T2, ``` SELECT DISTINCT name FROM T WHERE product IN ('a', 'b') AND name NOT IN (SELECT name FROM T ...
I know in T-SQL (MSSQL) you can use `EXCEPT` to exclude results: ``` SELECT Name FROM t WHERE Product IN ('a','b') EXCEPT SELECT Name FROM t WHERE Product NOT IN ('a','b') ``` `EXCEPT` also only returns `DISTINCT` results. See [SQL Fiddle](http://www.sqlfiddle.com/#!6/8835a/2). The second `SELECT` query after the ...
SQL include AND exclude query
[ "", "sql", "" ]
Consider the example table name "Person". ``` Name |Date |Work_Hours --------------------------- John| 22/1/13 |0 John| 23/1/13 |0 Joseph| 22/1/13 |1 Joseph| 23/1/13 |1 Johnny| 22/1/13 |0 Johnny| 23/1/13 |0 Jim| 22/1/13 |1 Jim| 23/1/13 |0 ``` In the above table, I have t...
To look into previous or following records, you would usually use the aggregate functions LAG and LEAD: ``` select first_name, work_date, work_hours from ( select first_name, work_date, work_hours , lag(work_hours) over (order by first_name, work_date) as prev_work_hours , lead(work_hours) over (order by fir...
Your problem (as phrased) is equivalent to asking: Is there a `1` that follows any given row with a 0 for a `name`? You can do this a correlated subquery: ``` select Name, Date, Work_Hours from (select t.*, (select min(date) from table t2 where t2.name = t.name and t2.date > t...
How to find rows with the sequence of values in a column using SQL?
[ "", "sql", "" ]
I have a table that has attendance of employee. This table has two columns: * first is the personnel number * second is the time of arrival I want to isolate the earliest time in this table, because an employee can register multiple times. Indeed I want to gain Least time of arrivalTime field for each personelNumber...
You're almost there. Just remove the `AttendanceTime` from the group by. ``` SELECT tal.PersonNo, min(tal.AttendanceTime) FROM mqa.T_AttendanceLog tal GROUP BY tal.PersonNo; ``` If you want the entire row (incase you have other columns) you can use something like this: ``` select * from mqa.T_AttendanceLog a ...
Modify your group by clause ``` SELECT tal.PersonNo,min(tal.AttendanceTime) FROM mqa.T_AttendanceLog tal GROUP BY tal.PersonNo ```
Separate rows based on a column that has min value
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
If I have several `LOJ`s and several `INNER JOINS` is there a correct **Standard** syntactical structure I should use? *Example scenario* * 5 tables #A - #E all with a UserId column and each with an additional column for a measure - MeasureA in table #A, MeasureB in table #B etc. * Tables #A, #B, #C all have the same...
When you are using left outer joins, the intention is that one of the tables is keeping all of its rows, regardless of matches in the other tables. My preferred structure is to put this table first: ``` select . . . from <really important table> t left outer join . . . ``` This doesn't work if you have inner jo...
As app developers, we trust frameworks, how come we can't trust SQL engines to do its work? The first syntax is what SQL is expecting, don't complicate it when not necessary. However, if A -> D is one to many; A -> E is one to many and there is no relation between D and E. I would GROUP BY the D and E matching rows in...
Standard approach when mixing several INNER with several LEFT OUTER JOINs
[ "", "sql", "" ]
I am attempting to speed up a query that takes around 60 seconds to complete on a table of ~20 million rows. For this example, the table has three columns (id, dateAdded, name). id is the primary key. The indexes I have added to the table are: ``` (dateAdded) (name) (id, name) (id, name, dateAdded) ``` The query I a...
There is a great Stack Overflow post on optimization of Selecting rows with the max value in a column: <https://stackoverflow.com/a/7745635/633063> This seems a little messy but works very well: ``` SELECT example1.name, MAX(example1.id) FROM exampletable example1 INNER JOIN ( select name, max(dateAdded) dateAdded fr...
why are you using index on many keys?? if your where clause contains only one column, then use that index only, put index on dateAdded and on name separately and then use in sql statement like this: ``` SELECT MAX(id) as id, name FROM exampletable USE INDEX (dateAdded_index) USE INDEX FOR GROUP BY (name_index) WHER...
Improving speed of SQL query with MAX, WHERE, and GROUP BY on three different columns
[ "", "mysql", "sql", "sqlperformance", "" ]
I have been searching around for the proper way of connecting into the database(MS ACCESS 2007) using VB6.0... The problem is it says an error that "SYNTAX ERROR IN INSERT INTO STATEMENT" DECLARATION CODE: ``` Dim adoConn As New ADODB.Connection Dim adoRS As New ADODB.Recordset Dim conStr, sqlStr As String ``` CONNE...
Escape the column names that match reserved words: `TIME` by enclosing in `[]`: ``` sqlStr = "INSERT INTO cur(CourseCode, Units, Days, [Time], RoomNumber, Instructor, Course, YearLevel, Term) VALUES (" ``` You should also use paramaterized queries as what you have in vulnerable to SQL Injection. (Run with a ' in one...
Unfortunately, you are using duplicate value.. I mean yor are trying to `INSERT INTO` to 9 columns(CourseCode, Units, Days, Time, RoomNumber, Instructor, Course, YearLevel, Term), however, you are putting 10 values(). `txtCurDays` is duplicated.
Cannot insert records to ms access 2007 with vb6
[ "", "sql", "database", "insert", "vb6", "" ]
I am creating an access log on my website, for whenever a person entering the site, he set the date and time whenever in the same registry in the database. however, instead of deleting the last visit, he added with the other. exemple: this is the current value: 2014-01-31 17:18:27 this is the new value: 2014-02-01 17...
You don't want to do this. Storing lists in SQL is not the right approach to using a database. You need a table that stores the dates in a separate table, with one row per `this` per `date`. If you had such a table, your code would be easy: ``` insert into ThisDateTable(this, date) select :this, :date; ``` That s...
``` Update TABLE SET COLUMN_NAME = COLUMN_NAME_A + COLUMN_NAME_B WHERE "Condition" ```
how can I add a value to the current with SQL UPDATE
[ "", "sql", "pdo", "sql-update", "" ]
At first I would like greet all Users and apologize for my english :). I'm new user on this forum. I have a question about MySQL queries. I have table Items with let say 2 columns for example itemsID and ItemsQty. ``` itemsID ItemsQty 11 2 12 3 13 3 15 5 16 1 ``` I need select itemsID but duplicated as many time...
**SQL answer - Option 1** You need another table called `numbers` with the numbers 1 up to the maximum for ItemsQuantity ``` Table: NUMBERS 1 2 3 4 5 ...... max number for ItemsQuantity ``` Then the following SELECT statement will work ``` SELECT ItemsID, ItemsQty FROM originaltable JOIN numbers ON originaltab...
``` Select DISTINCT items.itemsID, items.itemsQty From base.items left outer join (select items.itemsQty as Qty from base.items) As Numbers On items.itemsQty <=Numbers.Qty order by items.itemsID; ``` Use **DISTINCT** to remove duplicates. Read more here - <http://dev.mysql.com/doc/refman/5.0/en/select.html>
Duplicating rows in one select MySql query
[ "", "mysql", "sql", "multiple-records", "" ]
While explaining some concepts over CTE, was asked with a cute question.. can we find the multiplication of rows , while we always concentrate on the `SUM()` from a fresher. That gave me a thought! Is it ever possible with just an SQL. I was also considering the maximum number precision we can even support, since the p...
Oracle has exposed these [ODCI](http://docs.oracle.com/cd/B28359_01/appdev.111/b28425.pdf) (Oracle Data Cartridge Interface) methods to do the Aggregate! [Reference](http://docs.oracle.com/cd/B28359_01/appdev.111/b28425/ext_agg_ref.htm#CACJCHFF): * ODCIAggregateDelete() - Removes an input value from the current group....
The logarathm/power approach is the generally used approach. For Oracle, that is: ``` select exp(sum(ln(col))) from table; ``` I don't know why the original database designers didn't include `PRODUCT()` as an aggregation function. My best guess is that they were all computer scientists, with no statisticians. Such fu...
Product() aggregate function
[ "", "sql", "oracle", "statistics", "" ]
Simple enough, I'm trying to take information out of a Column in an SQL Database where the Members\_ID is equal to the integer the users inputs to a Textbox. * SendFromID.Text is the textbox containing the Members\_ID * Current\_Points is the textbox I want to hold/show the SQL Column info * U\_G\_Studio is the SQL Co...
I ended up with this code: ``` stcon = "CONNECTION STRING" con = New SqlConnection(stcon) da = New SqlDataAdapter("SELECT U_G_Studio FROM PersonsA WHERE Members_ID =" & SendFromID.Text, con) Dim dt = New DataTable da.Fill(dt) CurrentPoints.Text = dt.Rows(0)("U_G_Studio")....
Try something like this. [Using](http://msdn.microsoft.com/en-us/library/yh598w02.aspx) automatically takes care of disposing resources. Also parameterize your query to avoid sql injection attacks. ``` stcon = "CONNECTION STRING;" Dim strUGStudio As String Dim sql As String = _ "SELECT U_G_Studio FROM PersonsA WHERE ...
SQL To Text Box
[ "", "sql", "sql-server", "vb.net", "vba", "" ]
I'm very new to programming and SQL, I can't figure this one out, perhaps I haven't learned the concept yet, but I'm hoping you can help me. Sorry if it's too easy and boring. ``` /*2.37 Write an SQL statement to display the WarehouseID and the sum of QuantityOnHand,grouped by WarehouseID. Omit all SKU items that have...
"*Omit all SKU items that have 3 or more items on hand from the sum*", sounds more like : ``` FROM INVENTORY WHERE QuantitiyOnHand < 3 ``` rather than : ``` HAVING COUNT(WarehouseID) >= 3 ```
`INVENTORY` is the list of products (`SKU` = Stock Keeping Unit = Individual Product Stored in the warehouse) where every product has a `WarehouseID`. This `warehouseID` presumably determines where the product is stored. By **Omit all SKU items**, it asks you to only display those products that are stored in minimum 3...
Omit item from Sum SQL
[ "", "sql", "having", "" ]
[**Structure tables and result query on sqlfiddle**](http://sqlfiddle.com/#!3/d59e5/1) I want use query: ``` INSERT INTO Firm('name', 'name_original', 'id_city', 'id_service', 'id_firm') VALUES ('РЭД-АВТО ООО', 'РЭД-АВТО ООО', '73041', '2', '1429'), ('УМ-3 ЗАО ', 'УМ-3 ЗАО ', '73041', '2', '49806'), ('ООО West Hole',...
Remove the quotes around your column names. ``` INSERT INTO Firm(name, name_original, id_city, id_service, id_firm) VALUES ('РЭД-АВТО ООО', 'РЭД-АВТО ООО', '73041', '2', '1429'), ('УМ-3 ЗАО ', 'УМ-3 ЗАО ', '73041', '2', '49806'), ('ООО West Hole', 'РЭД-АВТО ООО', '73041', '2', '10004'); ```
For Example: `Insert into TableName ( Name,ID ) THEN Values ( 'Joe',2).` **Note:** The data type of column name should match with the data that you are inserting.
Sql Parameters supplied for object 'Firm' which is not a function
[ "", "sql", "sql-server", "sql-server-2008", "" ]
My tables are: ``` frequents(bar,drinker); likes(beer,drinker); serves(bar,beer) ``` I want to "select pairs of drinkers who frequents exactly the same bars".I think I can write that query using only the frequents table (as it has both bar and drinker column) using self joints I tried to do but couldn't get it.I don'...
THe easiest way in MySQL is to use `group_concat()` to put the values together and compare: ``` select fd.bars, group_concat(fd.drinker) as drinkers from (select f.drinker, group_concat(f.bar order by f.bar) as bars from frequents f group by f.drinker ) fd group by bars having count(*) > 1; ``` EDIT ...
This may help, however I'm using my knowledge from Microsoft SQL server. The syntax may differ from MYSQL. That being said you would need to JOIN the tables into themselves. ``` SELECT F.Bars, F.Drinkers, FB.Drinker FROM frequents F JOIN frequents FB ON (FB.Drinkers = F.Bars) WHERE FB.Drinkers = F.Drinkers ``` basi...
How to compare rows from same table in sql
[ "", "mysql", "sql", "" ]
I am not expert. I have following query, which contains 10 tables MainTable has 10 fields 1st Prime Key and rest foreign keys of 9 tables called TableE1 - 10. The following query is making outer join in each table, i want to optimize this query with index. I want to know, how can we optimize queries with index, this ...
Indexes are probably not going to help this query very much, because the query has no filtering. You are retrieving a million records. How much of the time spent on the query is retrieving the values and how much is spent processing the query? SQL Server has a good optimizer, that will use sophisticated join algorithm...
If your tables `TableE1`-`TableE9` have lots of records, you need to create an index on `RecID` in all nine tables. I guess you have many records and no indices currently, because 30 seconds is really slow for such a simple query.
How to optimize select query with index
[ "", "sql", "sql-server", "indexing", "query-optimization", "" ]
I have the following extract of a code used in SAS and wanted to write it in SQL Server to extract data. ``` substr(zipname,1,4) in("2000","9000","3000","1000");run; ``` How do I write this in SQL Server ? I tried and got this error: > An expression of non-boolean type specified in a context where a > condition is ...
In sql server, there's no `substr` function (it's [substring](http://msdn.microsoft.com/en-us/library/ms187748.aspx)) by the way, you need a complete query... ``` select blabla from blibli where substring(zipname, 1, 4) in ('2000', '9000', 3000', '1000') ``` assuming zipname is a varchar or something like that...
You need a table that you are getting the records from, and zipname would be a column in the table. The statement would be something like this: ``` select * from tablename where substring(zipname,1,4) in ('2000','9000','3000','1000') ```
how to use substr in SQL Server?
[ "", "sql", "sql-server", "sas", "" ]
I have two tables. table A: ``` code desc 001 sam 002 bob 003 mala 004 anna ``` table B: ``` code desc 001 marley 001 sam 002 bob 003 mala 004 anna 005 sana ``` I want to retrieve all the rows from both tables where the `code` value is common, regardless of the value of `desc`. That is, my final result...
Although I suspect you just want a MySQL option, here is the Oracle RDBMS solution. It uses a couple of neat features: the INTERSECT operator to produce a set of common values, and the WITH clause to improve the performance of the sub-query. It also employs the UNION operator which to produces a set of all the distinct...
You can do ``` SELECT a.code, a.desc FROM tablea a JOIN tableb b ON a.code = b.code UNION SELECT b.code, b.desc FROM tablea a JOIN tableb b ON a.code = b.code ORDER BY code, `desc` ``` Output: ``` | CODE | DESC | |------|--------| | 1 | marley | | 1 | sam | | 2 | bob | | 3 | mala ...
Retrieving duplicate from two tables in MySQL
[ "", "mysql", "sql", "oracle", "" ]
My problem is that Intellisense does not provide complete auto suggest for the columns that I have in my tables . Here is an example: ![sql 2012](https://i.stack.imgur.com/xMpYH.gif) As you can see on SSMS it does give me auto suggest for my tables, but does not for columns. I have read couple articles about solving...
IntelliSense can't predict which table you're going to select from, and will wait until you have at least one table in the FROM clause, and probably only until you specify an `alias.` before populating the columns in the case of a join or other multi-table query. There's a good reason for this. Imagine if you have `Cu...
First, that's because at the time of the screenshot SSMS does not know from what object you are selecting. In other words, it cannot guess what columns you're interested in when there is not a `from` clause in your `select` statement. If you try to type in the columns in the following `select` statement... ``` select ...
SQL Server 2012 Intellisense issue
[ "", "sql", "sql-server-2012", "" ]
I am executing the following sql. I get a syntax error which is (Incorrect syntax near '=') The query executes fine and gives proper results when executed normally. couldn't understand. plz take a look. ``` DECLARE @pvchMachineId VARCHAR(100) = '' DECLARE @pvchMake VARCHAR(100) = '' DECLARE @sql NVARCHAR(1000) SEL...
Update your query to the following ``` (@pvchMake = ''0'' OR m1.vchMake = @pvchMake) AND (@pvchMachineId = ''0'' OR m1.vchMachineId = @pvchMachineId) ``` than later when you go to execute just pass it in as parameters to sp\_executesql function. ``` EXEC sp_executesql @sql ,N'@pvchMachineId VARCHAR(100), @p...
This statement : ``` '(' + @pvchMake + '= ''0'' OR m1.vchMake = @pvchMake)' ``` Will output, since the variables are not initialized by anything else than `''` : ``` (= '0' OR m1.vchMake = @pvchMake) ``` Which is not correct syntaxically. You should use : ``` '(''' + @pvchMake + '''= ''0'' OR m1.vchMake = @pvchMa...
Dynamic sql is giving syntax error.
[ "", "sql", "sql-server", "t-sql", "" ]
I have a requirement to convert the binary number to decimal. The converted decimal range would be no greater than 256. (100 Million in binary) It involves an iOS app, where to read a problem investigation report, four binary integers are dynamically chosen and base on tht. (Some UI stuffs inside with 0s and 1s). The...
There are different ways you can approach this. So, I'm choosing what might seem like a rather arcane way. The motivation for this is that `to_number()` accepts hexadecimal formats but not binary formats. What would be so hard about supporting binary and octal as well as hex? Well, that's not a question for me to ask. ...
Just for fun, a version using a recursive CTE (so requires 11gR2), because apparently I look for any excuse to play with these at the moment: ``` with data as ( select '10.100.1.11' as str from dual ), t as ( select level as pos, regexp_substr(str, '[^\.]+', 1, level) as val from data connect by level <= regexp_c...
Convert binary to decimal in the given sequence
[ "", "sql", "oracle", "binary", "" ]
Am trying to access 2 tables values to single query. For Eg Customer name, id, Address to a single query. Customer address - State & Country in another table *Am trying to access all address to a single column in the query.* In Customer table state and country code only stored. Now I can able to access Customer name, I...
I'm not sure about MS Access syntax vs. SQL Server, but you can give this a shot: ``` SELECT CustomerName, CustomerId, ( (BFlatNo +','+ BPremises +','+ BStreet +','+ BArea +','+ BLocation +','+ BCity +','+ BState) +','+ (select top 1 CountryName from Country where CountryIdId=Customer.Country) ) AS Address FROM ...
If you want to `SELECT` from multiple tables then include the tables in the `FROM` clause or use a `JOIN`. ``` SELECT CustomerName, CustomerId, (BFlatNo & ',' & BPremises & ',' & BStreet & ',' & BArea & ',' & BLocation & ',' & BCity & ',' & BState & ',' & CountryName) AS Address FROM Customer IN...
Error in Sql Query in MS Access Database?
[ "", "sql", "ms-access", "" ]
I'm working within one table of a MS Access DB. I would like to use an iif statement to determine if a value from Field A conforms to a valid format (in this case, either one or two numbers followed by a letter). If it does, I would like to take just the numeric portion of Field A (e.g., if an entry for Field A is "15B...
For the pattern you described, you can build an update query with `like`, like this: ``` UPDATE tbl1 SET tbl1.ValB = Switch([ValA] Like "#[a-z]",Left([valA],1), [valA] Like "##[a-z]",Left([valA],2),True,NULL); ``` Or use the `Val` function, which will try to convert as much as possible from the string into a...
For the validation part of your question, you can use `Like` pattern-matching. Here is an example from the Immediate window. ``` ? "15A" Like "#[A-Z]" Or "15A" Like "##[A-Z]" True ? "4B" Like "#[A-Z]" Or "4B" Like "##[A-Z]" True ? "123A" Like "##[A-Z]" Or "123A" Like "##[A-Z]" False ? "15AB" Like "#[A-Z]" Or "15AB"...
Inserting part of a value from one field into another
[ "", "sql", "ms-access", "" ]
Here's my query: ``` INSET INTO cities (name, country_id) VALUES ('New York', 11), ('London', 215), ('Moscow', 66) ``` Is it right to say that rows will be inserted excactly in order of query? So, New Yor will be inserted first, than London, than Moscow. Is it possible that London will be inserted first? I can't find...
It is possible to return multiple values, so you could match them up that way, for example: ``` INSET INTO cities (name, country_id) VALUES ('New York', 11), ('London', 215), ('Moscow', 66) RETURNING id, name, country_id ``` just pick the columns you want to return.
the data are not stored in specified order.
INSERT multiple values in one query (order)
[ "", "sql", "postgresql", "" ]
I need to pass system function `MAX()` in `where` so I tried below code ``` select * from tb_sales_entry_total_product where Sno = MAX(Sno) ``` but it's showing error > An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being ag...
Use a sub-query: ``` SELECT p1.* FROM Tb_sales_entry_total_product p1 WHERE p1.Sno = (SELECT Max(p2.Sno) FROM Tb_sales_entry_total_product p2) ```
Try this: ``` select * from tb_sales_entry_total_product p1 where p1.Sno = (select MAX(p2.Sno) from tb_sales_entry_total_product p2) ```
How to use system function in where SQL Server 2008?
[ "", "sql", "sql-server", "" ]
well I am stuck with a simple but very irritating problem. I am creating a program that will save documents to *SharePoint*, when I click it will save the documents: ``` name, date, username, location version ``` to SQL. Now here is my problem. Each new documents version needs to increment/add by 1. So lets say we ...
``` @username varchar(100), @Type varchar(100), @Name varchar(100), @Version int, @Location varchar(100) as IF NOT EXISTS(select * from table where type = 'USERGUIDE') BEGIN SET @VERSION = 1 END ELSE BEGIN SET @VERSION = (SELECT MAX(VERSION) + 1 FROM table WHER...
The problem with your code is that you are always setting the Version Number to 1 before the insert: ``` SET @VERSION = 1 ``` You need to get the current max version from your table *prior* to the insert. Try this: ``` Declare @username varchar(100) = 'Wolf', @Type varchar(100) = 'pdf', @Name varchar(100) = 'doc', @...
how to add 1 to a value each time a new item is inserted SQL
[ "", "sql", "vb.net", "" ]
What is faster: Using a join to get userdetails for posts or only get the post data which includes the userid, collect the userIDs and after the posts are queried run one: SELECT x,y,z FROM users WHERE id in (1,2,3,4,5,6,7...etc.) Short: What is better?: ``` SELECT x,y,z,userid FROM posts WHERE id > x ORDER BY ...
anyway the second way is better: 1. You have only one call to database instead of two - so the channel between your DB and Application server is less loaded 2. Second way usually should be faster and less memory consuming because analyser can decide better how to manage its resources (it has all the requirements in on...
If I'm not wrong... normally dealing with INNER JOIN is more readable and cleaner.
Split a mysql query into two to avoid a join -> sum ids and use where in
[ "", "mysql", "sql", "join", "where-in", "" ]
Will my code work for solving the following problem? The total cost of all items ordered for all orders placed in July, 1996. Looking at 2 tables (`Orders` and `OrderDetails`) this is what I have so far. ``` SELECT Orders.OrderID, Customers.ContactName, Orders.OrderDate FROM Customers INNER JOIN ...
Try this: ``` SELECT o.OrderID, c.ContactName, o.OrderDate, SUM(od.Quantity * od.UnitPrice) AS grand_total FROM dbo.Customers c INNER JOIN dbo.Orders o ON c.CustomerID = o.CustomerID INNER JOIN dbo.[Order Details] od ON o.OrderID = od.OrderID WHERE o.OrderDate BETWEEN {ts '1996-07-01 ...
There are many ways to do this. GROUP BY ROLLUP - <http://technet.microsoft.com/en-us/library/ms177673.aspx> GROUPING SETS - <http://technet.microsoft.com/en-us/library/bb522495(v=SQL.105).aspx> OVER - <http://technet.microsoft.com/en-us/library/ms189461.aspx> Do not use Shiva's solution since COMPUTE is defunct in...
SQL Subtotal and Grand Totals
[ "", "sql", "sql-server", "" ]
I have a table with a id column, My query is ``` select id from tb_abc where title='xyz' ``` the result is ``` 1 3 6 8 ``` But what i want is to add a letter to id selected value like ``` 1d 3d 6d 8d ``` The letter d is fixed and declared in the query. Kindly guide.
``` select concat(id,'d') as id from tb_abc where title='xyz' ``` ### [SQLFiddle](http://sqlfiddle.com/#!2/d41d8/30679)
``` SELECT CONCAT(id,'d') AS id FROM tb_abc WHERE title = 'xyz' ``` This will work for you. Earlier as posted query for MSSQL.
Write a query to select a column with a additional letter
[ "", "mysql", "sql", "t-sql", "" ]
I have names of primary keys in a variable and I need to find the table to which they belong. The db has many table so linear search is not an option.
you can try this out :: ``` SELECT table_name FROM information_Schema.columns WHERE column_name='dept_id' and ordinal_position = 1; ```
You can use the `information_schema` tables. If the primary key name is the first column in the table, you can just do: ``` select table_name from information_schema.columns where column_name in (<your list here>) and ordinal_position = 1; ``` Otherwise, you have to go through the constraints to get what you wa...
How to find table name using primary key name in sql?
[ "", "sql", "sql-server", "t-sql", "key", "" ]
this is my table layout simplified: table1: pID (pkey), data table2: rowID (pkey), pID (fkey), data, date I want to select some rows from table1 joining one row from table2 per pID for the most recent date for that pID. I currently do this with the following query: ``` SELECT * FROM table1 as a LEFT JOIN table2 AS b...
You can try something on these lines, use the subquery to get the latest based on the date field (grouping by the pID), then join that with the first table, this way the subquery would not have not have to be executed for *each* row of Table1 and will result in better performance: ``` Select * FROM Table1 a INNER JOIN...
use the below code, and note that i added the order by Date desc to get the most resent data ``` select * from table1 a inner join table2 b on a.pID=b.pID where b.rowID in(select top(1) from table2 t where t.pID=a.pID order by Date desc) ```
tsql: alternative to select subquery in join
[ "", "sql", "sql-server", "" ]
Can anyone tell me what is going on in this function?? In the following code snippet, `user.Id = 0`, `id.Value = 0` and `id.SqlDbType = Int`.. as expected since `user.Id` is an int field. However, `error.Value = null` and `error.SqlDbType = BigInt`. What gives? If I use non-zero it detects an int and the correct value...
Both of the current answers are slightly incorrect because they're based on the assumption that the constructor being called for your `error` object is the [`(string,object)`](http://msdn.microsoft.com/en-us/library/0881fz2y%28v=vs.110%29.aspx) one. This is not the case. A literal `0` can be converted to any enum type1...
From [SqlParameter.Value on MSDN](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.value(v=vs.110).aspx) > For output and return value parameters, the value is set on completion of the SqlCommand i.e. I wouldn't rely on type inference to set the return type implicitly. I would explicitly set...
.NET SqlParameter constructor inconsistent?
[ "", "sql", ".net", "stored-procedures", "sqlparameter", "" ]
``` DECLARE @CityId AS VARCHAR(20) = NULL DECLARE @CityList AS VARCHAR(20) = '1, 2, 3, 4, 5'; IF (@CityId IS NULL) SET @CityId = @CityList; SELECT * FROM City WHERE CityID IN (@CityId) ``` I have a stored procedure that lists all cities. But If parameter is set, then it should display only specific information a...
You can use dynamic SQL ``` exec('SELECT * FROM City WHERE CityID IN (' + @CityId + ')') ```
Try this: ``` IF (@CityId IS NULL) SET @CityId = ',' + REPLACE(@CityList, ' ', '') + ','; ELSE SET @CityId = ',' + @CityId + ','; SELECT * FROM City WHERE charindex(',' + CAST(CityID as nvarchar(20)) + ',', @CityId) > 0 ```
SELECT Cities in stored procedure
[ "", "sql", "" ]
SQL query: ``` SELECT * FROM Account WHERE (type <>100000002 ? Id='something': Id=null) ``` but it shows error : > Incorrect syntax near '?' Please help me.
This is for SQL Server. `IIF` is not available in SQL Server 2008 or earlier. ``` SELECT * FROM Account WHERE Id=IIF(type<> 100000002,"something",null ) ``` If you are using SQL Server 2008 or earlier, then try this. ``` SELECT * FROM Account WHERE (Id= CASE WHEN type <>100000002 THEN 'so...
You can do this : ``` SELECT * FROM Account where (type <>100000002 and Id='something') or (type =100000002 and id is null) ``` or ``` SELECT * FROM Account where isnull(id,'_null_')= case when type <>100000002 then 'something' else isnull(id,'_null_') end ```
How to use ternary operator in SQL Server 2008?
[ "", "sql", "sql-server", "" ]
When I do this selcect: ``` SELECT tabuoj.id, tabuoj.tabuo, montritaj_tabuoj.id, montritaj_tabuoj.id_de_tabuo FROM tabuoj LEFT JOIN montritaj_tabuoj ON (tabuoj.id=montritaj_tabuoj.id_de_tabuo) ``` I get: ``` id | tabuo | id | id_de_tabuo | 1 | dom | 2 | 1 | 2 | samochód | null | ...
Try with `IS NULL` instead of `= null` like this ``` SELECT tabuoj.id, tabuoj.tabuo, montritaj_tabuoj.id, montritaj_tabuoj.id_de_tabuo FROM tabuoj LEFT JOIN montritaj_tabuoj ON (tabuoj.id=montritaj_tabuoj.id_de_tabuo) WHERE montritaj_tabuoj.id_de_tabuo is null ``` Reason: Actually `montritaj_tabuoj.id_de_tabuo is...
When you filter on a left joined table in the where clause, the join becomes an inner join. To solve the problem, filter in the from clause, like this: ``` FROM tabuoj LEFT JOIN montritaj_tabuoj ON (tabuoj.id=montritaj_tabuoj.id_de_tabuo) and montritaj_tabuoj.id_de_tabuo is null where clause starts here ```
WHERE coulmn.name=null doesn't return rows when left join
[ "", "android", "sql", "sqlite", "" ]
I need to get total number of visitors for each day & order them by date Below is a sample dates ``` NoOfBooking VisitDate 2 2014-01-21 11:16:28.490 2 2014-01-20 06:12:46.983 1 2014-01-19 11:28:24.743 2 2014-01-19 02:43:46.867 1 2014-01-18 16:24:25.200 2 ...
Try with this: ``` SELECT SUM(NoOfBooking) AS Total, cast(VisitDate as date) as VisitDate FROM Booking GROUP BY cast(VisitDate as date) order by VisitDate DESC ``` Adding `NoOfBooking` in your `group by` will produce incorrect results...
try this :: ``` SELECT SUM(NoOfBooking) AS Total, VisitDate FROM Booking GROUP BY NoOfBooking, date(VisitDate) order by VisitDate DESC ```
Total no of visitors dates wise not getting desired result
[ "", "sql", "sql-server-2008", "" ]
I'm new to SQL somewhat so bear with me if this is a n00b question. So my code runs something akin to the following: ``` (select "Balance."CodeValue" AS "CodeValue" , "Balance"."OtherValue" AS "OtherValue" from "SomeDB"."dbo"."AValue" "Balance" where ("Balance"."CodeValue" between 'A' and'Z' or "Balance"....
As written above you are correct, the first bit isn't doing anything because it's negated by the last bit: ``` ;WITH cte AS (SELECT 'XYZ' AS CodeValue UNION SELECT 'A') SELECT * FROM cte WHERE (CodeValue between 'A' and'Z' or CodeValue in ('ABCDEFG')) AND CodeValue NOT in ('XYZ', '...
``` select Balance.CodeValue AS CodeValue ,Balance.OtherValue AS OtherValue from SomeDB.dbo.AValue Balance INNER JOIN SomeMatrix on SomeMatrix.CodeValue = Balance.CodeValue where ( Balance.CodeValue between 'A' and'Z' ----\ OR -- Either of this is true Balance.CodeV...
SQL - Clarification of Between and NOT IN Combo
[ "", "sql", "sql-server", "between", "notin", "" ]
I'm working on a school assignment that wants me to insert some new values into a database table and then print a message based on whether or not the INSERT was successful. The question goes like this: > Write a script that attempts to insert a new category named “Guitars” > into the Categories table. If the insert i...
I would use try/catch myself ``` begin try insert query print message end try begin catch print message end catch ``` You should be able to take it from here.
``` USE MyGuitarShop GO BEGIN TRY -- Insert the data INSERT INTO Categories (CategoryName) VALUES ('Guitars') PRINT 'SUCCESS: Record was inserted.' END TRY BEGIN CATCH PRINT 'FAILURE: Record was not inserted.'; PRINT 'Error ' + CONVERT(VARCHAR, ERROR_NUMBER(), 1) + ': '+ ERROR_MESSAGE() END CAT...
SQL syntax for checking to see if an INSERT was successful?
[ "", "sql", "sql-server", "database", "insert", "sql-server-2012", "" ]
SQL Server to show if field1 is null then field2, if field1 and field2 are null then field3, if field1, field2, field3 are null then field4 if all 4 fields are null then NULL How would this be displayed in SQL Server? I am assuming maybe a case statement and do case when etc but I am lost on this. EDIT -- I tried runn...
COALESCE Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL. ``` SELECT COALESCE(field1, field2, field3, field4) FROM yourtable ``` # [COALESCE](http://msdn.microsoft.com/en-us/library/ms190349.aspx) Or You can use CASE Statement ``` SELEC...
You're looking for the [COALESCE](http://msdn.microsoft.com/en-us/library/ms190349.aspx) operator ``` SELECT COALESCE(field1, field2, field3, field4) ```
text, ntext, and image data types cannot be compared or sorted
[ "", "sql", "sql-server", "" ]
I have a table like this ``` SA_ID ---+---Acct_Id---+---SA_Type 101 111 TYPE1 102 111 TYPE2 103 112 TYPE1 ``` I have a query to get acct\_id having more than one sa\_type ``` select acct_id,count(*) from sa_tbl having count(*) > 1 group by acct_id; ``` I g...
I tried to get result like you mentioned in question but able to get something similar to this check it on [SQL Fiddle](http://sqlfiddle.com/#!2/a54af4/1) ``` SELECT tbl.`Acct_Id` AS 'Acct_Id',COUNT(`Acct_Id`) AS 'counts', GROUP_CONCAT(`SA_Type`) AS 'types' FROM `sa_tbl` AS tbl GROUP BY tbl.`Acct_Id` HAVING counts ...
Check the pivot function, see question here [MySQL pivot table](https://stackoverflow.com/questions/7674786/mysql-pivot-table) This function works for Oracle and MySQL. For other databases (if you need) you can check additionally by yourself.
Select different values of a column having count more than one
[ "", "sql", "" ]
I have two datasets `a` and `b` each with fields for cusip and ticker. The **sql** i'd like to perform would take `a` column from set `b` `if a.cusip=b.cusip`, but if i cannot find a match for the cusip, i'd like to take the column from `b` `if a.ticker=b.ticker`. Is there an easy way to execute this? I'm having troub...
Inner join and Or in your where Clause condition should do the job. ``` Select * from a inner join b on a.cusip=b.cusip or a.ticket = b.ticket; ```
You'll need to join to your B table twice, once on cusip and once on ticker. Then you can use `coalesce` to take the first non-null value. ``` select coalesce (b_cusip.column, b_ticker.column), ... from a left outer join b b_cusip on a.cusip = b_cusip.cusip left outer join b b_ticker on a....
Multiple case merge sql
[ "", "sql", "merge", "sas", "" ]
I can't get rid of this error. I have added the "NT AUTHORITY\NETWORK" user via SSMS, along with the relevant roles using this thread as reference: [Login failed for user 'NT AUTHORITY\NETWORK SERVICE'](https://stackoverflow.com/questions/2251839/login-failed-for-user-nt-authority-network-service) I am trying to make ...
First read [this description of the security limitations](http://technet.microsoft.com/en-us/library/hh510202.aspx#sectionToggle5) of using LocalDB. Reading that make me think that it may not be possible to use "NT AUTHORITY\NETWORK SERVICE"; I'm not sure. I think you'll need to use your credentials. Not to be too obv...
in that link that you used as reference I think Jed gave the correct answer to your problem. Try it. You should add 'NT AUTHORITY\NETWORK SERVICE' not 'NT AUTHORITY\NETWORK'. I think the default user for windows services is Local Service. So try to add 'NT AUTHORITY\LOCAL SERVICE'. You could also try to change user t...
The login failed. Login failed for user 'NT AUTHORITY\NETWORK
[ "", "sql", "sql-server", "" ]
Given is the following table: ``` CREATE TABLE public.parenttest ( id bigserial NOT NULL PRIMARY KEY, mydata varchar(30), parent bigint ) WITH ( OIDS = FALSE ); ``` I'd like to insert a bunch of rows. Some of these rows should take the sequence-generated `id` of a row inserted before as value for t...
Here's how I'd do it, if it's acceptable for the rows to briefly have a `NULL` parent: ``` INSERT INTO parenttest (mydata) VALUES ('rootnode'), ('child1'), ('child2'), ('child2.1'), ('child2.2'); UPDATE parenttest SET parent = (select id from parenttest pt where (pt.mydata = 'rootnode' and parenttest.mydata in ('ch...
You could do something as ugly as: ``` INSERT INTO parenttest (mydata,parent) VALUES ('rootnode',null); INSERT INTO parenttest (mydata,parent) SELECT 'child1', id FROM parenttest WHERE mydata='rootnode'; INSERT INTO parenttest (mydata,parent) SELECT 'child2', id FROM parenttest WHERE mydata='rootnode'; INSERT INTO pa...
How to insert rows which optionally have parent rows in the same table at once
[ "", "sql", "postgresql", "postgresql-9.2", "" ]
I'm trying to calculate and list the websites in order of biggest overall reduction in response time from one time period to the next. I don't strictly need to use a single query to do this, I can potentially run multiple queries. websites: ``` | id | url | | 1 | stackoverflow.com | | 2 | s...
Using a couple of sequence numbers:- ``` SELECT a.id, a.url, MAX(100 * (LeadingResponse.response_time - TrailingResponse.response_time) / LeadingResponse.response_time) FROM ( SELECT website_id, created_at, response_time, @aCnt1 := @aCnt1 + 1 AS SeqCnt FROM responses CROSS JOIN ( SELECT @aCnt1:...
You need the equivalent of the `lag()` or `lead()` function. In MySQL, I do this using a correlated subquery: ``` select website_id, max(1 - (prev_response_time / response_time)) * 100 from (select t.*, (select t2.response_time from table t2 where t2.website_id = t.website_id a...
SQL: Find the biggest percentage change in response time
[ "", "mysql", "sql", "statistics", "" ]
Say I have following results ``` ---------------------- | col1 | col2 | ---------------------- | a | b | | b | a | | c | d | | e | f | ---------------------- ``` I would like to get distinct tuple regardless of column order. In other words, (a, b) and (b, a) ...
Try it this way ``` SELECT DISTINCT LEAST(s1.country, s2.country) c1, GREATEST(s1.country, s2.country) c2 FROM battles b1 JOIN battles b2 ON b1.battlename = b2.battlename AND b1.ship <> b2.ship JOIN ships s1 ON b1.ship = s1.name JOIN ships s2 ON b2.ship = s2.name HAVING c1 <> c2 ``` Out...
Here is how you can do it Sample data ``` | COL1 | COL2 | |------|------| | a | b | | b | a | | c | d | | e | f | ``` Query ``` SELECT k.* FROM test k LEFT JOIN (SELECT t.col1 FROM test t INNER JOIN test r ON (r.col1 = t.col2 ...
Show distinct tuples regardless of column order
[ "", "mysql", "sql", "distinct", "" ]
I have a table called Locations that looks like this ``` Name Date Location A 01/01/2014 Location A 12/12/2013 Location B 01/01/2014 Location C 01/01/2014 Location D 01/01/2014 Location D 12/12/2013 Location E 12/12/2013 ``` I want to return only the Names where the date is MAX(Date) i.e. 01/01/2014 and where t...
This seems to work: ``` declare @t table (Name varchar(49), [Date] date) insert into @t(Name,[Date]) values ('Location A','20140101'), ('Location A','20131212'), ('Location B','20140101'), ('Location C','20140101'), ('Location D','20140101'), ('Location D','20131212'), ('Location E','20131212') select Name,MAX(Date) ...
We can first check the names which are not repeating using `GROUP BY` and `COUNT` in inner query and then `inner join` this one with original table over which we group by name and date to calculate max value dates and corresponding name ``` SELECT t.Name, MAX(Date) From table INNER JOIN (SELECT DISTINCT Name from tab...
SQL - Only choose unique names by max date?
[ "", "sql", "sql-server-2008", "sql-server-2008-r2", "" ]
I am trying to insert records into table B from table A, where the records don't already exist in table B. Only some of the fields I need are in table A, so I have set up some local variables to insert the data for these. On running the query below, I get the error message "Msg 8114, Level 16, State 5, Line 17 Error c...
SELECT has columns in wrong order ``` select @SupplierID, @UnitOfMeasurementID, @MinOrderQuantity, @SupplierProductGroupID, @ProductCondition, PartNumber, ProductName, CostPrice from BearmachTemp source where not exists ( select * from tblProduct where tblProduct.PartNumber =...
In Insert Statement Insert columns and values should have the same Order, so : ``` insert into tblProduct (SupplierID, UnitOfMeasurementID, MinOrderQuantity, SupplierProductGroupID, ProductCondition, PartNumber, ProductName, CostPrice)...
SQL insert using select from .. where not exists and local variables in the select clause fails
[ "", "sql", "sql-server", "" ]
I have two tables, one with users and another with errors. They have 2 relations. Errors can be fixed or submited by users. I want to show usernames with submited and fixed errors. I tried something like this: ``` SELECT usr.username, err.description AS ERROR_SOLVED FROM Users usr, Errors err WHERE err.solved_by_id=u...
The columns must have the same descriptions. ``` SELECT usr.username, err.description AS ERROR, 1 as SOLVED FROM Users usr, Errors err WHERE err.solved_by_id=usr.id UNION SELECT usr.username, err.description AS ERROR, 0 as SOLVED FROM Users usr, Errors err WHERE err.submited_by_id=usr.id ``` would work. You can also...
Something like this... ``` Select usr.username, submittedErrs.description AS ERROR_SUBMITTED, fixedErrs.description AS ERROR_SOLVED from Users usr left outer join Errors submittedErrs ON submittedErrs.submitted_by_id=usr.id left outer join Errors fixedErrs ON fixedErrs.solved_by_id=usr.id ```
How to do select with 2 conditions into two columns
[ "", "sql", "" ]
I am working on a long query, here is a portion of it: ``` SELECT '3' AS RowType ,DTH.EnteredBy AS Person ,COALESCE(PDT.[Name], APP.AppName) AS Project ,( CASE WHEN ( STY.KanBanProductId IS NOT NULL AND STY.SprintId IS NULL ) THEN 'Kanban'...
You can either use 'Cross Apply' or CTE (Common Table Expression) to do this. I prefer Cross Apply so here is an example that way: ``` SELECT '3' AS RowType ,DTH.EnteredBy AS Person ,COALESCE(PDT.[Name], APP.AppName) AS Project ,CAResult.ProjectType ,dbo.primaryTheme(STY.[Number], CAResult.ProjectType)...
You can either repeat the query, it will be executed only once, or you can use a sub-query/ CTE: ``` WITH CTE AS ( SELECT '3' AS RowType ,DTH.EnteredBy AS Person ,COALESCE(PDT.[Name], APP.AppName) AS Project ,( CASE WHEN ( STY.KanBanProductId IS NOT NULL ...
Passing logic of previous column as parameter
[ "", "sql", "sql-server", "" ]
Hi my query getting this error help me to recover it ``` SELECT CompanyId, CompanyName, RegistrationNumber, (select CompanyAddress from RPT_Company_Address where RPT_Company_Address.CompanyId=Company.CompanyId) AS CompanyAddress, MobileNumber, FaxNumber, CompanyEmail, CompanyWebsite, VatTinNumber FROM Company...
It appears that your RPT\_Company\_Address table has more than one address for a given company. If this should not be possible, you should try to correct the data and modify your schema to prevent the possibility of this happening. On the other hand, if there can be multiple addresses, you must decide how your query s...
Your subquery below is returning more than one result ``` select CompanyAddress from RPT_Company_Address where RPT_Company_Address.CompanyId = Company.CompanyId ``` Therefore more than one address matches your company id. Try fixing the data or using: ``` select top 1 CompanyAddress from RPT_Company_Address whe...
At most one record can be returned by this subquery. (Error 3354)
[ "", "sql", "ms-access", "" ]
Ok, so I have a query that is returning more rows than expected with repeating data. Here is my query: ``` SELECT AP.RECEIPTNUMBER ,AP.FOLDERRSN ,ABS(AP.PAYMENTAMOUNT) ,ABS(AP.PAYMENTAMOUNT - AP.AMOUNTAPPLIED) ,TO_CHAR(AP.PAYMENTDATE,'MM/DD/YYYY') ,F.REFERENCEFILE ,F.FOLDERTYPE ,VS.SUBDESC ,P.NAMEFIRST||' '||P.NAMELAS...
The cause is that at least one of the connections `ACCOUNTBILLFEE-FOLDER` or `VALIDACCOUNTFEE-ACCOUNTBILLFEE` is not one-to-one. It allows for one *Folder* to have many *AccountBillFees* or for one *ValidAccountFee* to have many *AccountBillFees*. To find the cause of such a problem this is what I usually do: * Chang...
Try this if it helps then those tables have additional rows which are not relevant. If it doesn't then look at the results of the subqueries I have below to see what additional filters are needed ``` SELECT AP.RECEIPTNUMBER ,AP.FOLDERRSN ,ABS(AP.PAYMENTAMOUNT) ,ABS(AP.PAYMENTAMOUNT - AP.AMOUNTAPPLIED) ,TO_CHAR(AP.PAYM...
Last two joins cause duplicate rows
[ "", "sql", "sql-server", "join", "" ]
Suppose that you are given the following simple database table called Employee that has 2 columns named Employee ID and Salary: ``` Employee Employee ID Salary 3 200 4 800 7 450 ``` I wish to write a query select max(salary) as max\_salary, 2nd\_max\_salary from employ...
You can just run 2 queries as inner queries to return 2 columns: ``` select (SELECT MAX(Salary) FROM Employee) maxsalary, (SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )) as [2nd_max_salary] ``` [SQL Fiddle Demo](http://sqlfiddle.com/#!2/2445c/2)
Try like this ``` SELECT (select max(Salary) from Employee) as MAXinmum),(max(salary) FROM Employee WHERE salary NOT IN (SELECT max(salary)) FROM Employee); ``` **(Or)** Try this, n would be the nth item you would want to return ``` SELECT DISTINCT(Salary) FROM table ORDER BY Salary DESC LIMIT n,1 ``` In your cas...
Find max and second max salary for a employee table MySQL
[ "", "mysql", "sql", "" ]
I have two tables (`entity` and `kind`) plus a n:m table (`entity_kind`). ``` CREATE TABLE entity ( entity_id INT , name NVARCHAR(100) , PRIMARY KEY(entity_id) ) CREATE TABLE kind ( kind_id INT , name NVARCHAR(100) , PRIMARY KEY(kind_id) ) CREATE TABLE entity_kind ( entity_id INT...
This is a compare two sets of things type problem. The query I'm going to show gives all pairs along with a flag. You can easily incorporate comparing a subquery by changing the first two `entity` tables to the table of ids you want to compare. This query has a few parts. First, it produces all pairs of entities from ...
You can do this with two checks: First, if the kind-count on each entity is not the same, then they cannot match. Second, provided the count is the same, you just need to find one kind that doesn't match the list of an arbitrary other entity (I just take the first entity in the compare list). In code: ``` DECLARE @fir...
How to compare n:m assignments?
[ "", "sql", "sql-server", "" ]
I just got a query cod : ``` SELECT o.id,o.sort_order,od.object FROM i_objects o, i_objects_description od WHERE o.id=od.objects_id AND o.object_status = ? AND od.languages_id = ? ORDER BY o.sort_order ASC ``` I want figure it out what does "?" mean in this query ? If I run this query , it gives me this error : ``...
It's a placeholder for parameter. In your query you have this: ``` AND o.object_status = ? AND od.languages_id = ? ``` And then you execute it like this: ``` $res = $sth->execute( array( 'active', $language_id ) ); ``` So, when query is actually executed by database server, `object_status` is `'active'` and `langua...
The `?` are placeholder the values of which are filled in in the `$sth->execute( array( 'active', $language_id ) )` statement. One of the main purposes for this construct is to prevent *sql injection attacks*.
What does it mean "?" in sql query?
[ "", "sql", "pear", "" ]
Not even sure to word this, which is probably why I can't immediately think of a solution, however… I have a table of store locations and a second table which are the stats which record, amongst other things, which stores have appeared in 'find my closest store' type searches. So, for instance, table A has this conte...
You have a very poor format for the `stats` table. You should have a second table for "StatsIds". Here is the way to phrase your join: ``` SELECT COUNT(a.ID) as Total, a.ID, a.Store_Name FROM a join b on find_in_set(a.id, b.Search_Results) > 0 group by a.ID; ``` Unfortunately, this query cannot be optimize...
One option I can think of is: ``` SELECT stores.id, stores.name, (SELECT count(*) FROM stats WHERE stats.search_results like '%' | stores.id | '%') hit_count FROM stores ``` I don't have a database to try this, but I think this should work
Query to count number of times an id appears in string
[ "", "mysql", "sql", "" ]
**Schema and data** I have two tables with the following schema and data: *#table1:* ``` create table #table1( PK int IDENTITY(1,1) NOT NULL, [TEXT] nvarchar(50) NOT NULL ); PK TEXT 1 a 2 b 3 c 4 d 5 e ``` *#table2:* ``` create table #table2( PK int IDENTITY(1,1) NOT NULL, ...
From my perspective this is equivalent of ``` select isnull(table2.text, table1.text) as text from ... ```
You should check whether a field is null or not by `is null`, even though your `case when` is syntactically correct, you should use the other syntactically correct version. ``` case when #table2.[TEXT] is null then #table1.[TEXT] else #table2.[TEXT] end ```
Unexpected result in SELECT CASE WHEN NULL
[ "", "sql", "sql-server-2008", "select-case", "" ]
I have 2 Tables.. **User 1** ``` user_id mobile_no 1 1111 2 2222 ``` **User 2** ``` user_id mobile_no 1 3333 2 2222 ``` I Want to first UNION These tables, then group by and then want to count total records I am using this query but it's not working ``` SEL...
This is weird. No one seems to have realised it's as simple as: ``` select count(*) overall from (select mobile_no from user1 union select mobile_no from user2) ``` The difference between `union` and `union all` is that `union` removes duplicates.
Try this: ``` SELECT COUNT(*) FROM ( (SELECT * FROM user1) UNION (SELECT user_id as u1,mobile_no as m1 FROM user2) ) as a1 GROUP BY a1 .1 ```
UNION All, Group BY and then get overall COUNT
[ "", "mysql", "sql", "group-by", "union", "" ]
This is my database table structure: ``` ----------------------------------- | id | title | date | ----------------------------------- | 001 | my event OO1 | 04/02/2014 | | 002 | my event OO2 | 04/02/2014 | | 003 | my event OO3 | 04/02/2014 | | 004 | my event OO4 | 05/02/2014 | | 005 | my event OO5 | 05/...
``` SELECT distinct t1.date, (SELECT t2.ID, t2.title FROM mytable as t2 WHERE t2.date = t1.date ORDER BY RAND() LIMIT 1) AS event_title FROM mytable as t1 ORDER BY t1.date; ```
Use: ``` SELECT d1.date, ( SELECT d2.title FROM table_1 d2 WHERE d2.date = d1.date ORDER BY RAND() LIMIT 1 ) AS title FROM table_1 d1 GROUP BY d1.date HAVING COUNT(d1.date)>=1 ORDER BY d1.date ASC ``` The only thing you should need to change is the name of your table. Make sure you only table ...
Display random results ordered by date
[ "", "sql", "random", "sql-order-by", "" ]
I have a mysql table with country, state, city and locality. I want to get only those countries which are having either city or locality as null or empty. I tried this query: ``` select distinct country from xyz where state != "" and ((city="" and Locality="") or (city="" and Locality!="") or (city!="" and Locality=""...
Are you looking for a simple `or`: ``` select distinct country from xyz where state <> '' and (city = '' or Locality= '') order by country; ``` If this doesn't return what you want, you might have a problem with `NULL` values: ``` select distinct country from xyz where state <> '' and (city = '' or Local...
``` select distinct country from xyz where state != "" and (city="" or Locality="") ```
get specific records based on where condition
[ "", "mysql", "sql", "" ]
I want to write a query where it deletes duplicates from table where the Access column value is 1 - 5, but always take the highest number but if it's 5 then that should be the lowest, because of how they designed the database. but 5 have no access.(5 should have been 0 in my opinion.) So there is an ID column and an A...
If you apply modulo 5 to the Access column, you will get the following transformation: ``` 1 % 5 = 1 2 % 5 = 2 3 % 5 = 3 4 % 5 = 4 5 % 5 = 0 ``` As you can see, 5 yields the lowest result, others remain unchanged – seems the proper ranking of privileges for your case. With that in mind, I would probably try the follo...
If you want to delete the row for each id that first has access 5 and the rest ordered, then do: ``` with todelete as ( select t.*, row_number() over (partition by id order by (case when access = 5 then -1 else access end) ) as seqnum ...
Delete row with a complex if
[ "", "sql", "sql-server", "" ]
I have tables: ``` 'gallery' - information about existing galleries id_gallery name date ========== ==== =========== 1 ... timestamp 'photo' - information and name of every photo in system id_photo photo_name ======== =========== 1 some name 'photo_gallery' - "connecting" table, w...
Please try the following query: ``` SELECT galery.*, photo.* FROM galery LEFT JOIN photo_gallery ON galery.id = photo_gallery.id_gallery LEFT JOIN photo ON photo_gallery.id_photo = photo.id GROUP BY galery.id ```
use LIMIT ``` SELECT pg.id_photo FROM gallery g LEFT OUTER JOIN ( SELECT id_gallery, MAX(id_photo) AS id_photo photo_gallery pg GROUP BY id_gallery ) AS pg ON g.id_gallery = pg.id_gallery ```
Select first joined value, not all
[ "", "mysql", "sql", "" ]
I'm trying to implement [this askTom solution](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:185012348071) to count the business days between two date fields in a table. ``` select count(*) from ( select rownum rnum from all_objects where rownum <= to_date('&1') - to_da...
This is not like the original askTom, but if you're using 11gR2 you can use a Recursive CTE: ``` with rcte(a,b, i, is_wd) as ( select from_dt , to_dt , id, case when (to_char(from_dt, 'DY') in ('SAT','SUN')) then 0 else 1 end from t union all select decode(a, null, a,a+1), b, i, case when (to_char(a, 'DY') in ('SA...
Try this one: ``` SELECT COUNT(*) FROM ( SELECT ROWNUM rnum FROM all_objects WHERE ROWNUM <= TO_DATE('2014-02-07','yyyy-mm-dd') - TO_DATE('2014-02-01','yyyy-mm-dd')+1 ) WHERE TO_CHAR( TO_DATE('2014-02-01','yyyy-mm-dd')+rnum-1, 'DY' ) NOT IN ( 'SAT', 'SUN' ) ``` However, it has at least two...
Counting business days between two dates for each row in a table
[ "", "sql", "oracle", "" ]
I am using `oracle10g`. I want to remove all occurrences of particular word from sentence, But I don't want to remove any other word which contains other characters between a-z or A-Z. **For example**, Following is a sentence from which I want to remove `some`: ``` some text, 123 someone, another text some1 ``` **E...
Due to lack of support for [lookbehind/lookahead](http://www.regular-expressions.info/lookaround.html) and [word boundary(`\b`)](http://www.regular-expressions.info/wordboundaries.html) in Oracle implementation of regular expression, it seems to be impossible to meet all requirements in single [`REGEXP_REPLACE`](http:/...
Here is an approach that doesn't use regular expressions: ``` select trim(replace(' '||'some text, 123 someone, another text some1'||' ', ' some ',' ' ) ) from dual; ```
remove specific word from string
[ "", "sql", "regex", "oracle", "replace", "" ]
I'm working with a recursive table and I'm trying to build a query to get my child node counts however my query fails to return the correct count when I restrict it by the `basic_user_id`. The idea behind the design is to enable different users to have their own hierarchy of companies, however I can't have them conflic...
Could you try this? You can test here. <http://www.sqlfiddle.com/#!2/73f61/2> I have added `AND child_tab.basic_user_id = parent_tab.basic_user_id` ON clause. Because You are doing `LEFT JOIN` ``` SELECT parent_tab.company_id, COUNT(child_tab.company_id) FROM company_user parent_tab LEFT JOIN company_user child_tab ...
Resolved, I just needed to add a second join. ``` select * , count(c2.company_id ) from deepblue.company_user c1 left join deepblue.company_user c2 on c2.parent_id = c1.company_id and c1.basic_user_id = c2.basic_user_id where c1.company_id in (1337) and c1.basic_user_id= 541 group by c1.company_id; ```
Getting child node count from mysql query
[ "", "mysql", "sql", "aggregate-functions", "hierarchical-data", "" ]
I want to take the first row (postgresql 9.2) : ``` SELECT posts.employee_id, posts.month, posts.year FROM posts WHERE ((posts.month = 9 AND posts.year = 2013) OR (posts.month IS NULL AND posts.year IS NULL)) ORDER BY posts.employee_id ``` But it returns: ![Execution of the query](https://i.st...
Not exactly sure how `MAX` behaves in PostgreSQL but something like this would work in `SQL-server`: ``` SELECT posts.employee_id, max(posts.month) as "month", max(posts.year) as "year" FROM posts WHERE (posts.month = 9 AND posts.year = 2013) OR (posts.month IS NULL AND posts.year IS NULL) GROUP BY ...
``` SELECT posts.employee_id, posts.month, posts.year FROM posts WHERE posts.employee_id = 1 AND (posts.month = 9 AND posts.year = 2013) OR (posts.month IS NULL AND posts.year IS NULL) ORDER BY month DESC NULLS LAST LIMIT 1 ``` [**From Documentation**](http://www.postgresql.org/docs/8.3/static/queries-order.html)...
SQL WHERE (contains or equal)
[ "", "sql", "postgresql", "" ]
Thanks everyone for the input, especially during the closing hours of the bounty, it's been incredible helpful. *This is a followup question to [Select courses that are completely satisfied by a given list of prerequisites](https://stackoverflow.com/questions/20671624/select-courses-that-are-completely-satisfied-by-a-...
In my opinion modeling conjunction and disjunction in one table is always uneasy and leads to either violation of normal form or inability to predict how many self joins are necessary. What I understand is that your prerequisites can be generally always expressed as alternatives of conjunctions. So the following: ``` ...
> Kuba Wyrostek has suggested below to enumerate all prerequisite combinations for each course into distinct sets. While this would work, I need to do this for ~6k rows, each with many enumerations. Is there a more efficient way to accomplish this? Storing sets is an obvious choice, I agree with Kuba. But I suggest a ...
Compound course prerequisites (One or more of a,b,c and either x or y as well as z style)
[ "", "mysql", "sql", "prerequisites", "relational-division", "" ]
I need to display the keyboard players from a list of bands, and I've been able to using the following SQL: ``` SELECT BAND.NAME AS Band_Name, KBPLAYER.NAME AS Keyboard_Player FROM BAND FULL OUTER JOIN ( SELECT M.NAME, MO.BID FROM MEMBEROF MO, MEMBER M WHERE MO.INSTRUMENT='keyboards' AND M.MID=MO.MID ...
I've decided to do it differently since I wasn't going anywhere with the above SQL. I'll appreciate if anyone has suggestions to make for the above SQL with the set constraints. ``` SELECT band.name AS Band_Name, 'NULL' AS Keyboard_Player FROM memberof INNER JOIN member ON memberof.mid = member.mid FULL JO...
Use the [coalesce](http://www.postgresql.org/docs/current/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL) function. This function returns the first of it's arguments that are not null. Eg: ``` COALESCE(KBPLAYER.NAME,'No KeyBoard Players') AS Keyboard_Player ```
SQL Replace NULL Values with Own text
[ "", "sql", "postgresql", "" ]
I have a database and my dataset is really messed up. The column of importance is the a "uniqueidentity" number where some records have "&&" or "%%" in contained at the end of the value. If it does, I would like to delete the entire row from the table. uniqueidentity = VARCHAR Does anybody have any ideas on how to do ...
you could use ``` DELETE FROM table WHERE RIGHT(uniqueidentity, 2) = "&&" OR RIGHT(uniqueidentity, 2) = "%%" ```
Try like this: ``` DELETE FROM tableName WHERE uniqueidentity REGEXP '%%$' OR uniqueidentity REGEXP '&&$'; ``` I have created supporting [SQL FIDDLE](http://sqlfiddle.com/#!2/a2c1d6/5) with select query which you can change it to delete as above.
Deleting all rows which contain a unique value
[ "", "mysql", "sql", "" ]
Work on sql server 2008 r2. Want to join table=**ValueTable** and table= **DateRangeTable** .Both table data as like as picture .There is no strong relation between them ,Need to update **ValueTable** column on range of **DateRangeTable** column **StartDate** and **EndDate**. ![enter image description here](https://i....
Try this and let me know your comments/Results ``` UPDATE ValueTable SET IncRange=DRT.IncRange FROM ValueTable VT INNER JOIN DaatRangeTable DRT ON VT.BillDate >= DRT.StartDate AND VT.BillDate <=DRT.EndDate ```
You can use an `update...select` query like below ``` update ValueTable set ValueTable.incRange = drt.incRange from DateRangeTable drt where ValueTable.BillDate >= drt.StartDate and ValueTable.BillDate <= drt.EndDate ```
How to update tables with in date range
[ "", "sql", "t-sql", "sql-server-2008-r2", "" ]
hi i wrote this query in SqlServer 2008 but some thing goes wrong ``` select * from News_Table where (DATEDIFF( DAY ,convert(datetime, NewsDate) , convert(datetime,@Todaydate )) <= @Count) ``` that `@NewsDate` and `@Todaydate` are two nvarchar parameters that are saved like this `2014/11/16` running this query give ...
Try adding the correct style parameter to your convert function (see MSDN: [link](http://msdn.microsoft.com/en-us/library/ms187928.aspx) ) ie `CONVERT(DATETIME, NewsDate, 111)` (111 is the style for YYYY/MM/DD) Then you get: ``` SELECT * FROM News_Table WHERE (DATEDIFF( DAY , CONVERT(DATETIME, New...
To know more [click here](http://networking.ringofsaturn.com/SQL/howtoformatdatetime.php) ``` SELECT convert(datetime, '2014/11/16', 111) as datetime ``` **OP** ![enter image description here](https://i.stack.imgur.com/nshwX.png) So your query would be like this ``` Select * from News_Table where (DATEDIFF( DAY ,c...
how to convert nvarchar(50) to datetime in sqlserver 2008
[ "", "sql", "sql-server", "sql-server-2008", "datetime", "converters", "" ]
I want split text from NAME column and insert comma separated data to PARCA column for each row. ex: ``` name parca ---- ------------- john j,jo,joh,john ``` Code: ``` DECLARE @i int = 0 WHILE @i < 8 BEGIN SET @i = @i + 1 update export1 set PARCA = cast ( PARCA as nvarchar(max)) + ...
Create this function: ``` create function f_parca ( @name varchar(100) ) returns varchar(max) as begin declare @rv varchar(max) = '' if @name is not null select top (len(@name)) @rv += ','+ left(@name, number + 1) from master..spt_values v where type = 'p' return stuff(@rv, 1,1,'') end ``` Testing the function `...
``` DECLARE @Count INT,@I INT SET @I = 1 SET @Count = LEN('SURESH') DECLARE @N VARCHAR(2000) SET @N = '' WHILE @Count > 0 BEGIN SET @N = @N + ','+SUBSTRING('SURESH',1,@I) SET @I = @I+1 SET @Count = @Count -1 END SELECT SUBSTRING(@N,2,2000) ``` The above code is only a sample.'SURESH' is your name field...
Split text value insert another cell
[ "", "sql", "sql-server", "database", "t-sql", "" ]
Using SQLCe, I have a column of DateTime type. I would like to filter just by year. Is it possible or should I store year separately, which seems to me redundant? E.g. get distinct results of 2010,2011,2013. Thanks
think you have the `DATEPART` function (but not the `YEAR` function) so ``` select DatePart(yyyy, <yourDateTime>) ``` or if that's for ordering, of course ``` order by DatePart(yyyy, <yourDatetime>) ``` **EDIT** ``` select max(InvoiceID) from yourTable where DatePart(yyyy, IssuedDate) = 2013 ```
The usual way to do this is to use a range filter: ``` select * from table where datecolumn >= '2012/01/01' and datecolumn < '2013/01/01' ``` This has the benefit that any index you may have on `datecolumn` can be used. Since the answer you accepted shows that you only care about one single year, your objection to t...
Select "YYYY" component only from DateTime column
[ "", "sql", "datetime", "select", "" ]
I have a table which records each event in a system such as 'Queued', 'Started', 'Finished', 'Failed' etc... There are a lot more steps in the table but these are all I am interested in. I select from this only the events I want ``` SELECT [Id] ,[EventTime] ,[Message] FROM [Log] WHERE [Message] LIKE '%Queued%' OR [M...
You can achieve this with multiple LEFT OUTER JOINs, but be aware that the performance can be bad if your're having a lot of data. Queurying the *message* column with LIKE is not a really good idea as well from a performance viewpoint. Did you think of using some kind of ETL tool to prepare the data before loading it ...
you have a missing variable for grouping all those logs in to one session. in your query they may be several logs with status "Started" so you need to have a "requestId" or something similar that will contain 1 log from each type.
SQL grouping records from a log table
[ "", "sql", "sql-server", "" ]
How do I realize the following in MySQL with Triggers: When value of some column is null -> set other column values to null and when value of some column is not null -> set other column values to null table definition: ``` CREATE TABLE variations ( id int(10) NOT NULL, x1 int(10) NOT NULL, x2 int(10), x1_optio...
This is syntax for trigger: ``` delimiter // CREATE TRIGGER upd_check BEFORE UPDATE ON account FOR EACH ROW BEGIN IF NEW.amount < 0 THEN SET NEW.amount = 0; ELSEIF NEW.amount > 100 THEN SET NEW.amount = 100; END IF; END;// delimiter ; ``` ...and your ...
you seem to have ";" set as DELIMETER, which causes the query to execute once it sees a ";". try changing it first: ``` DELIMITER // CREATE TRIGGER check_null_x2 BEFORE INSERT ON variations FOR EACH ROW BEGIN IF NEW.x2 IS NULL THEN SET NEW.x2_option1 = NULL; SET NEW.x2_option2 = NULL; END IF; END;// DELIMITER ; ```
MySQL Trigger usage : if column is null set other column null
[ "", "mysql", "sql", "" ]
I'm doing multiple inserts in a **single** query: ``` INSERT INTO table (c1, c2) VALUES (1,2), (2,3), (3,4),...... ON DUPLICATE KEY UPDATE c2 = VALUES(c2) ``` Now suppose that there's over tens of thousands of VALUES specified in the query (...
[ACID](https://en.wikipedia.org/wiki/ACID) (Atomicity, Consistency, Isolation, Durability) properties are used to describe such behaviour in databases. Atomicity is only important if we're dealing with [concurrent modifications](https://en.wikipedia.org/wiki/Concurrency_control). To ensure Consistency, a certain level ...
*"Can there ever be a case in which some parts of the VALUES managed to get inserted/updated in the database but the rest did not get inserted/updated possibly due to some sort of db error/failure/memory-running-out etc?"* Late answer, but perhaps interesting: `[ON DUPLICATE KEY] UPDATE` is not *strictly* atomic for s...
Are mysql multiple inserts within a Single query atomic?
[ "", "mysql", "sql", "insert", "sql-update", "atomic", "" ]
How to get sysdate in following format in SQL Server? > 1/1/2014 > > 1/2/2014 > > 1/3/2014 i.e **`M/D/YYYY`** I searched in google, i got different formats, but i want following format. Please help me. Thanks.
Have a look at the CONVERT documentation in msdn article [here](http://msdn.microsoft.com/en-us/library/ms187928.aspx) You can see many formats here. For your case use ``` SELECT CONVERT(NVARCHAR(20),yourdate,101) as formatteddate ``` Based on your question edit I would recommend `datepart` and associated functions ...
Use this Code: ``` SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY] ``` OR ``` SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [M/D/YYYY] ```
How to get sysdate with different formats?
[ "", "sql", "sql-server", "" ]
``` select datepart(yyyy,hiredate) as Hire_Date_of_Year,jobTitle,count(jobTitle) as Number_Of_Title from [AdventureWorks2012].[HumanResources].[Employee] group by jobTitle,hiredate having hiredate like '2004%' order by jobtitle asc ``` ## Above is my code. the Output I am getting is this ``` Hire_Date_of_Year jobT...
You shouldn't really do date comparisons using `like`. That is best used on strings. Here is a way to write the query you want: ``` select datepart(yyyy, hiredate) as Hire_Date_of_Year, jobTitle, count(jobTitle) as Number_Of_Title from [AdventureWorks2012].[HumanResources].[Employee] where datepart(yyyy, hireda...
You need to group by the Year, not the full date ``` SELECT DatePart(yy, hiredate) As Hire_Date_of_Year , jobTitle , Count(jobTitle) As Number_Of_Title FROM [AdventureWorks2012].[HumanResources].[Employee] WHERE DatePart(yy, hiredate) = 2004 GROUP BY DatePart(yy, hiredate) , jobTitle ```
I need a SQL Query which group by employee with year,
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
Sorry for Title, don't know how to explain. ![enter image description here](https://i.stack.imgur.com/jtzH7.png) Ok so I want to see if any protocol (PTC\_ID) is linked to an Audit (AUD\_ID), in the picture you can see there is 3 tables and each one has a value of the other. I though of using `inner join` all 3 tabl...
try ``` select ptc.ptc_name, aud.aud_year from ptc_table ptc inner join ada_table ada on ada.ada_ptcid=ptc.ptc_id inner join aud_table aud on aud.aud_id=ada.ada_aud_id ```
``` Select AUD_YEAR From AUD_Table at Inner Join ADA_TABLE ad ON at.AUD_ID = ad.ADA_AUD_ID Inner Join PTC_TABLE pt ON pt.PTC_ID=ad.ADA_PTCID ```
Get ID from another table through a table
[ "", "sql", "sql-server", "" ]
Could someone verify my understanding of proc sql union operations? My interpretation of the differences between outer union and union is the following: 1. Union deletes duplicate rows, while outer union does not 2. Union will overlay columns, while outer union, by default, will not. So, would there be any difference...
It turns out there is, actually, a difference: how columns which only exist in one dataset are handled. `Outer Union Corresponding` will display columns that appear only in one dataset, not overlaid by position. `Union All Corresponding` will not display any columns that appear in only one dataset.
My understanding is that `OUTER UNION` and `UNION ALL` are effectively if not actually identical. `CORR` is needed for either one to guarantee the columns line up; with `OUTER UNION` the columns will not stack even if they *are* identical, while with `UNION ALL` the columns *always* stack even if they are not identical...
Any difference between union all corresponding and outer union corresponding?
[ "", "sql", "sas", "" ]
I have a table named Category\_tbl ``` Id Categoryname info ``` subcategory\_tbl ``` id categoryid subcatname info ``` product\_tbl ``` id subcat info ``` i in here subcategory\_tbl has the category id and product\_tbl has subcategory id as subcat.now if i want to delete a category then i all the corresponding ...
First delete the data from the tables which have foreign key and then the table with primary key..Using multiple delete statements...
Without [cascading deletes](https://stackoverflow.com/questions/12185811/mysql-on-delete-cascade-test-example) on the foreign keys, what you can do this as a sequence of deletes from `subcategory` through `product` and finally `category`. Assuming you wish to delete category 123: ``` delete from product_tbl where sub...
how to delete from another 2 table using one key?
[ "", "mysql", "asp.net", "sql", "" ]
I tried this code - ``` UPDATE Table SET Name = RTRIM(LTRIM(Name)) ``` Data type of Name is `varchar(25)` None of the leading and trailing spaces get removed. When I copy-paste one such `Name`, i get this - ``` "big dash" "space symbol" ABC001 ``` Why is this happening and how do trim the spaces ? **EDIT -** The...
I suspect, some non readable(Non-ascii characters) inside the name column, that might not get removed as part of `TRIM` calls. ``` select convert(varbinary, Name) from table ``` Reading the `HEX` output from above query should reveal the same. Kindly read [this](http://iso30-sql.blogspot.com/2010/10/remove-non-print...
Kindly use below query it will remove space new line etc.. ``` select LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(Name, CHAR(10), CHAR(32)),CHAR(13), CHAR(32)),CHAR(160), CHAR(32)),CHAR(9),CHAR(32)))) ```
Trim spaces in string - LTRIM RTRIM not working
[ "", "sql", "sql-server", "" ]
I have two tables `posts` and `posts_replies` I queried all posts and order them by timestamp (post time). Now I want to do the following : Any time a user make a reply for any post I want to put that post at the top of the wall so I did get the max replies' timestamp of each post and order the posts using the max time...
MySQL has an [`IF()`](http://dev.mysql.com/doc/refman/5.5/en/control-flow-functions.html#function_if) function, that you may also use in the `ORDER BY` clause: ``` ORDER BY IF(column IS NULL, othercolumn, column) ``` in your case it would be: ``` ORDER BY IF(f1.recent_reply_time IS NULL, posts.timestamp, f1.recent_r...
`SORTING` is easily readable and maintainable, if you make it based on what you select. Better have some `sortkey` in your select and use it in `ORDER BY`. i have used `COALESCE` to handle nulls. Makes ure sortkey atleast have one `NOT NULL` value, by using suitable arguments to COALESCE ``` SELECT posts.*, u...
How to order a query by column if some of its values are null?
[ "", "mysql", "sql", "query-optimization", "" ]
I have a table like so: ``` create table t1 ( id_a int id_b int dt datetime ) ``` Sample data might be: ``` id_a id_b dt 39838 6 2014-01-21 11:20:29.537 39838 546 2014-01-21 11:20:29.790 39839 4088 2014-01-21 11:20:31.543 39795 6 2014-01-21 11:20:33.117 39795 546 2014-01-21 11:20:34.100 39795 3189 2...
You can accomplish this by using Parition by clause: ``` SELECT IB_B, COUNT(ID_A) NO_OF_TIMES FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ID_A ORDER BY DT) AS ROW_NO FROM T1)TEMP WHERE ROW_NO = (SELECT TOP 1 ROW_NO+1 FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ID_A ORDER BY DT) AS ROW_NO FROM T1)TEMP WHERE ib...
This will also work in SQL Server 2008: ``` WITH cte AS ( SELECT id_a, id_b, ROW_NUMBER() OVER (ORDER BY dt) AS rn FROM t1 ) SELECT TOP 1 t2.id_b, COUNT(*) AS cnt FROM cte AS t1 JOIN cte AS t2 ON t2.rn = t1.rn+1 WHERE t1.id_b = 6 GROUP BY t2.id_b ORDER BY COUNT(*) DESC ```
how to select which id comes second the most often in sql server
[ "", "sql", "sql-server", "" ]
I have two tables that store email information: * EMAIL * EMAIL\_ADDRESS EMAIL has: * email ID * timestamp * and other info we don't care about EMAIL\_ADDRESS has: * ID (foreign key references EMAIL.ID) * EMAIL\_ADDRESS * TYPE (to, from) Say I have 6 rows in EMAIL - the query should return the ID, timestamp, to a...
You must distinct EMAIL\_ADDRESS table to two view: ``` SELECT eat.EMAIL_ADDRESS as to ,ea.EMAIL_ADDRESS as from, e.ID, e.sent_date FROM EMAIL_ADDRESS ea, CHANN_EMAIL e,EMAIL_ADDRESS eat WHERE e.ID=ea.id and e.ID=eat.id AND ea.TYPE in ('from') AND eat.TYPE in ('to') ```
try using `GROUP BY e.ID` or `GROUP BY ea.id`
Select multiple column values in single query - oracle
[ "", "sql", "oracle", "" ]
I download The world database from <http://downloads.mysql.com/docs/world.sql.gz> However when I pasted all the content in the sql file into phpMyAdmin to create the tables, error shows: ``` #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right synta...
Try this zip file for dump world database <http://gyankosh.siplstudio.com/wp-content/uploads/2014/02/worlddump-1.sql_.zip>
check the single quotes on the question mark try '?' instead of '?
MySQL the world database sql file has syntax error when inserting data
[ "", "mysql", "sql", "" ]
Suppose today is Thursday. I have 1 flag for both Wednesday and Friday. If I create a temporary table then it will look like ``` ID WeekDay XFlag ================================== 1 Mon 0 2 Tue 0 3 Wed 1 4 Thu 0 5 Fri 1 6 Sat 0 ...
So you want the next day but the challenge is that the week days form a cycle. You can handle this using `order by` and some cleverness: ``` select top 1 tt.* from TemporaryTable tt where flag = 1 order by (7 + tt.id - datepart(dw, getdate())) % 7 ``` [Here](http://www.sqlfiddle.com/#!6/d41d8/14549) is a SQL Fiddle. ...
I've gone quite procedural here, but the parts can be incorporated into a larger query, rather than using local variables, if required: ``` declare @t table (ID int not null,Weekday char(3) not null,XFlag bit not null) insert into @t(ID,WeekDay,XFlag) values (1,'Mon',0),(2,'Tue',0),(3,'Wed',1), (4,'Thu',0),(5,'Fri',1)...
Algorithm to get next weekday based on today
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]